Note: In CSS3 flexbox is way more powerful then below methods. Learn more about flexbox here .


Horizontal Content Centering

The most common and (therefore) easiest type of centering is that of lines of text in a paragraph or in a heading. CSS has the property named text-align for that. The text-align property describes how inline-level content of a block container is aligned. We write it like -

p { text-align: center; }


More values for this property are:

  1. For left alignment of inline-content
  2. For center alignment of inline-content
  3. For right alignment of inline-content
  4. For stretches spaces and words in inline boxes.
  5. Takes parents property value

But the problem is this property specially works for ‘text’ type contents.

But if you want centered align of any content on a container, you just can use this piece of code.

Say, we want centered align a image on a container.

  .container img {
      margin: 0 auto;
      display: block;
  }

See the Pen CSS-Centering things Vertically & Horizontally by Md. Nadimozzaman Pappo (@mnpappo) on CodePen.


Vertical Content Centering

This is the most critical part. We can use the property vertical-align: middle for contents on a table. But for other contents its usually cause problem. I found this great solution at last. Lets have a look -

For a document that looks like this: (Example taken from W3C)

  <div class="container">
    <img src="http://placehold.it/50x50">
  </div>

the style sheet looks like this:

  div.container {
     height: 10em;
     position: relative;                (1)
     border: 1px dotted red;
  }
  div.container p {
     position: absolute;                (2)
     top: 50%;                          (3)
     transform: translate(0, -50%);     (4)
     left: 50%;
  }

What happened there & how to:

  1. Make the container relatively positioned, which declares it to be a container for absolutely positioned elements.
  2. Make the element itself absolutely positioned.
  3. Place it halfway down the container with top: 50%. (Note that 50%’ here means 50% of the height of the container.)
  4. Use a translation to move the element up by half its own height. (The ‘50%’ in ‘translate(0, -50%)’ refers to the height of the element itself.)

See the Pen CSS-Centering things Vertically & Horizontally-2 by Md. Nadimozzaman Pappo (@mnpappo) on CodePen.

This works for any type of content. You can use the property height: auto; for flexible height. In that case the content will be centered vertically against the height of the container.


Here are some more links given for more awesome examples & guides :

  • http://www.w3.org/Style/Examples/007/center
  • http://www.w3.org/TR/css-align-3/#overview
  • http://www.w3schools.com/cssref/pr_pos_vertical-align.asp

Republished from: My old blog