Centering a div to the middle of the web page?
21,658
Solution 1
to center a div both hor and ver you could do this way:
markup
<div class="centered"></div>
css
.centered{
position:absolute;
width:100px;
height:100px;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}
fiddle: http://jsfiddle.net/steweb/qSvAQ/1/
Solution 2
<div class = 'middle'></div>
.middle{
margin: auto;
width: 900px;
}
Author by
Registered User
Updated on July 09, 2022Comments
-
Registered User almost 2 years
I want to make my div be positioned in the middle-center part of the web page. I'm attempting to make a pre-loader div which should be in the middle-center part of the web page and after the page loads, that div will be hidden. How can I achieve such?
The div should be centered horizontally and vertically.
-
GusDeCooL over 13 yearsCorrect answer. remember to set your width, if not the div will assume it width is 100% an the center will not show.
-
Spyros over 13 yearsexactly, you can set it according to your liking, 900px is just an example here.
-
Registered User over 13 yearsdoes this center it vertically as well?
-
Spyros over 13 yearsnop, this is horizontal, vertical align would need absolute positioning. To be sincere, i don't really recommend it unless really needed, but you may want to take a look : jakpsatweb.cz/css/css-vertical-center-solution.html
-
Registered User over 13 yearsThis did the trick for me.. Thanks! :) I hope this doesn't break in other browsers beside Firefox though...
-
immutabl over 13 yearsI've been waiting 12 years to see this bit of CSS - you can't imagine the sorts of kludges I've had to get into to get things centred in the past. Tsk.
-
stecb over 13 yearsYou're welcome.. it works in all browsers ;) IE6 - who cares - too I think (can't test it right now)
-
stecb over 13 years@SpyrosP why you don't recommend it? What's wrong with an absolute positioned div centered used to show a loader?
-
Spyros over 13 yearsIt's not that i do not recommend the technique, there's nothing with it. My problem is that absolute positioning tends to be kinda sloppy and can cause some weird problems if not properly handled. To show a loader, as in your case, it would be pretty fine. Once again, i stress that the technique is just fine.