Code solutions to PHP, JS, CSSCode source PHP, JS, CSS

Spread your code soluces to the world

Love me
Solucior » CSS » Centering an element in the page

Centering an element in the page

09/15/2011 by Dux   -   4/5 (1 ratings)

Here are two methods to center CSS DIV blocks inside the page or parent element.
The first method uses absolute positioning wich does not consider the position of other page elements. It is recommended for a rapid implementation of a correctly set graphical template.
The second method uses a div to wedge the second DIV in height. The horizontal centering is specified by automatic left and right margins. Please do not forget the DTD to make this work in IE.

See a demonstration of this script in action :

Open in a new window     Open in the same window

source code



 
<style type="text/css">
html, body {
       
margin: 0;
       
padding: 0;
       
width: 100%;
       
height: 100%;
}

/* Method 1 : absolute position */
.centered {
       
position: absolute;
       
top: 50%;
       
left: 50%;
       
height: 250px;
       
width: 400px;
       
margin: -125px 0 0 -200px;
       
background: red;
}

/* Method 2 : with another DIV */
.top_page {
       
height: 50%;
       
margin-bottom: -150px;
}
.
centered2 {
       
height: 300px;
       
width: 500px;
       
background: limegreen;
       
margin: 0 auto;
}

</
style>

<
div class="top_page">Your texte page here</div>
<
div class="centered2">Method 2</div>


<
div class="centered">Method 1</div>


Tested with Safari  Google Chrome  Firefox3  Firefox4  Opera  IE6  IE7  
Rate this code     |     Copied : 29x

Comments for Centering an element in the page

No comment
Add a comment Nickname
ZOOM