Monday, 1 April 2013

Centering An Image Or Text Within A Div

This post explains how to center an image or text in HTML using CSS. The code example is available on GitHub in the Center-Image-Text-Div directory.

Centering An Image Vertically And Horizontally Within A Div

The method described here requires to know the size of the image. The HTML is the following:
<div id="myDiv">
    <img id="myImg" src="SomeImg.jpg">
</div>
The CSS is the following:
#myDiv {
    height: 100%;
    width: 100%;
}

#myImg {
    position: absolute;
    top: 50%;
    left: 50%;
    /* My image height divided by 2 */
    margin-top: -47px;
    /* My image width divided by 2 */
    margin-left: -188px;
}
The image is always positioned at the center of the window, even when it is resized. This example is inspired from the solution provided by deviousdodo on a StackOverflow question.

Centering Text Within A Div

The HTML is the following:
<div id="width:100%">
    <div id="someText">This text is always centered!</div>
</div>
The CSS is the following:
#someText {
    width: 300px;
    margin: 0px auto;
    text-align: center;
}
One must set a width larger than the text, and set the text alignment to centered.