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;
}
Share:
21,658
Registered User
Author by

Registered User

Updated on July 09, 2022

Comments

  • Registered User
    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
    GusDeCooL over 13 years
    Correct answer. remember to set your width, if not the div will assume it width is 100% an the center will not show.
  • Spyros
    Spyros over 13 years
    exactly, you can set it according to your liking, 900px is just an example here.
  • Registered User
    Registered User over 13 years
    does this center it vertically as well?
  • Spyros
    Spyros over 13 years
    nop, 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
    Registered User over 13 years
    This did the trick for me.. Thanks! :) I hope this doesn't break in other browsers beside Firefox though...
  • immutabl
    immutabl over 13 years
    I'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
    stecb over 13 years
    You're welcome.. it works in all browsers ;) IE6 - who cares - too I think (can't test it right now)
  • stecb
    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
    Spyros over 13 years
    It'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.