Reputation: 165282
I'm looking for a valid cross-browser solution for an HTML page which:
<div>
which will hold the main contentI know vertical centering is possible when the wrapping container has a static height. Is adjusting this height to browser window height something feasable? (Preferably, no JS should be used.)
Upvotes: 11
Views: 16107
Reputation: 38431
Depends on what you mean with "cross browser". Following works fine with all current, standards compatible ones (thus not IE6):
HTML:
<div id="a">
<div id="b">
<div id="content"></div>
</div>
</div>
CSS:
html, body, #a {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
#a {
display: table;
}
#b {
display: table-cell;
margin: 0;
padding: 0;
text-align: center;
vertical-align: middle;
}
#content {
border: 5px solid red;
width: 100px;
height: 100px;
margin: auto;
}
Live example:
Upvotes: 24
Reputation: 6441
Is simply not possible without JavaScript, at least not with CSS2 or earlier (not sure if CSS3 makes this possible, someone clarify on that).
The other provided answers require absolute width and height for the element; I assumed no such requirement. There's no way to center a flowing element vertically which is what you usually want, given that you don't know the aspect ratio of the browser window to reliably use fixed-size containers for content.
Upvotes: 0
Reputation: 175
You could do something like this. It looks to work in IE6 as well:
<html> <head>
<script type="text/javascript"> </script>
<style type="text/css">
#container { height: 100%; width: 100%; position: relative; }
#content {
border: 5px solid red;
width: 100px;
height: 100px;
position: relative;
margin-left: -50px;
margin-right: -50px;
top: 50%;
left: 50%; }
</style>
</head> <body>
<div id="container">
<div id="content"></div> </div>
</body> </html>
Upvotes: 0