How-to: Center with CSS

In this article I will explain how to:

  • Centering Text with CSS
  • Centering Image with CSS
  • Centering Div with CSS
  • Vertically Centering Element with CSS
  • Positioning div to center of browser window

Centering Text with CSS

Supposing you have a paragraph with "center" class

<p class="center">Paragraphy</p>

You should use text-align property to center the text.

p.center{
    text-align: center;
}

Centering Image with CSS

Although the image in <p></p> tags can be centered by using text-align property as above, but it's not recommended.

Instead, you should tell the browser the image is a block, then you can center it like a block.

Here is the HTML of a image with "center" class.

<img src="sample.jpg" class="center" />

And here is the CSS

img.center {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

Centering Div with CSS

You already know what to do after you tell browser that image is a block, div is also a block.

Here is the HTML of a div with "center" class

<div class="center">I am a div</div>

You may still apply the margin-left, margin-right trick, difference is DO NOT forget to define width for your div, then the div will center itself inside the containing element.

div.center {
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

This will also work for any block has a defined width.

Vertically Centering Element with CSS

You need to place the elements you want to center inside a containing element, such as a DIV.

HTML, a div with "vcenter" class, contains a paragraph to be centered

<div class="vcenter">
    <p>Vertically centering</p>
</div>

In CSS part, you need to set a minimum height for the container, tell the browser it is a table-cell now, then the vertical-align property will start working.

.vcenter {
    min-height: 100px;
    display: table-cell;
    vertical-align: middle;
}

Positioning div to center of browser window

Now we knew how to center element both horizontally and vertically, but how to position a div to the exact center of browser window, center it both horizontally and vertically in the mean time? Just combine 2 tricks above? Here is a better solution.

<div class="exactCenter"></div>

The trick is using fixed position, by setting top: 50%, left: 50% you positioned the top-left corner to center of browser window, then you set margin-topmargin-left to minus value to compensate.

margin-top = -width/2
​margin-left = -height/2

.exactCenter {
    width:200px;
    height:200px;
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    background-color: #00FF00;
}

Leave a Reply