Hello,
I want to center a div right in the middle of the page, I tried top:30%
, but when the window is resized off the alignment.
<div id=cent></div>
Thanks Jean
Hello,
I want to center a div right in the middle of the page, I tried top:30%
, but when the window is resized off the alignment.
<div id=cent></div>
Thanks Jean
<div id="content"
style="text-align: center;
vertical-align: middle;
border-color: #000000;
border-width: 1px;
border-style: solid;
margin-top: 25%;
margin-bottom: 25%;">
hi
</div>
This worked for me...
Edit : This will align the whole div... regardless of the size of the div or the page... Assuming that this id the only div in the whole page...
If you know the height/width of that div (for instance, it will be 100px X 200px) then you can do it like this:
#cent {
position:absolute;
top:50%;
left:50%;
margin-top:-50px; /* this is half the height of your div*/
margin-left:-100px; /*this is half of width of your div*/
}
UPDATE: another option: see http://www.w3.org/Style/Examples/007/center (Centering vertically)
Adding notes to naivists' link (to w3c tips site):
display:table-cell
does not work with height:100%
. So, if you want to vertically center an element, which you don't know its height, on a page, you need to put it inside a container with display:table
and height:100%
, and another container with display:table-cell
and vertical-align:middle
.
Furthermore, if you want to center it horizontally, you need to specify width:100%
to body, the outer container, and give text-align:center
to inner container. The content should have display:inline-block
, and to reset alignment, text-align:left
.
Ultimately, it becomes as follows:
<style>
#vcontainer {
display: table;
height: 100%;
width: 100%;
}
#hcontainer {
display: table-cell;
vertical-align: middle;
text-align: center;
}
#content {
display: inline-block;
border: lightGray 1px solid;
background-color: lightBlue;
text-align: left;
}
</style>
<body>
<div id="vcontainer"><div id="hcontainer">
<div id="content">
Hoyjo!<br>
I have returned to my hometown!<br>
Lolololo lololo lololo lololo lololo!<br>
</div>
</div></div>
</body>
I cannot guarantee it will work on legacy browsers (IE6/7). It will work on IE8 provided it runs on IE8 standards (yes, this will screw your mind. Thanks, MS!), and you must give <html>
and <body>
the height:100%
.
Here's how:
#cent
{
margin-left:50px;
margin-right:50px;
}
Now your div is going to be 50px from left and right and centered in whatever container you have it in.