tkalve 30

How can I horizontally and vertically center a div of unknown height? I know I can use the following CSS to vertically center a div vertically:

div {
    height: 400px;
    top: 50%;
    margin-top: -200px;
}

How can I do this with a div of fluid height?

1 answer

Mottie 1134
1
point

All divs are automatically set to 100% width, but you can use CSS to center them horizontally, but you won't be able to tell unless the div is smaller than 100% width.

div { margin: 0 auto; width: 90%; }

To center the div of unknown height vertically, I think that can only be done with javascript. Here is how I would do it with jQuery

$(document).ready(function(){
 $('#content').css('margin-top' , $(window).height()/2 - $('#content').height()/2 );
})
Answered almost 7 years ago by Mottie
  • +1 to what Fudgey said. However, do make sure that if you're using IE to declare a !DOCTYPE. Otherwise using `margin: 0 auto;` will not work. DondeEstaMiCulo almost 7 years ago