Horizontal and vertical centering
2012/05/20 Css resources, examples & tutorials for webmasters and online professionals
Horizontal and vertical centering
html, body{ height: 100%; }
container{ left: 50%; top: 50%; margin-left: -500px; margin-top: -300px; }
Sometimes you want a website (or an element) to center both horizontally and vertically. It is actually very simple doing this with css.
Important to know is that not all browsers set the body of the site to 100% height. So, before centering your page you you need to start by setting the page's body height to 100%.
Example of the css code
html, body{
height:100%;
margin:0;
}
#container{
position: absolute;
width: 1000px;
height: 600px;
text-align: center
left: 50%;
top: 50%;
margin-left: -500px; /* half of the width of your container element */
margin-top: -300px; /* half of the height of your container element */
}
As always you place this preferably in your stylesheet file or in the head of your document (wrapped in the <style></style> tag).
Example of the html code
<body>
<div id="container"><img src="image.jpg" alt="Image" width="1000" height="600"/></div>
<body>
This will center your page horizontal and vertical and works in most modern browsers.
Summary
Avoid the old tables and use css stylesheets to center your webpage. As long as you remember to set the body's height to 100% both vertical and horizontal centering will work in most browsers.
Leave a reply.