Centering items using CSS is actually very easy. If you want to center a picture horizontally then just use the following code in your CSS file.
IMG.centered {
display: block;
margin-left: auto;
margin-right: auto;
}
What the above CSS code does is center an image between the left and right margins automatically. Whenever you insert an image just make sure to call the “centered” class, for example:
<img class=”centered” src=”/images/someimage.jpg” alt=”some text” />
If you want to center something vertically then you would need to use a container. For example:
DIV.container {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: fixed;
display: table;
}
P {
display: table-cell;
vertical-align: middle;
}
Now that you have the CSS part done lets look at the HTML part.
<div class=”container”>
<p>This text is vertically centered</p>
</div>
Now lets combine both of the techniques together to have an image that is horizontally and vertically centered in a browser window.
CSS Code:
DIV.container {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: fixed;
display: table;
}
P {
display: table-cell;
vertical-align: middle;
}
HTML Code:
<div class=”container”>
<p>The image below is vertically and horizontally centered.<br />
<img class=”centered” src=”images/someimage.jpg” alt=”some text” /></p>
</div>
Thats It!