Tuesday, 18 February 2014

Centering Made Easy

Almost a note-to-self today. :-) Now that IE6 and IE7 are dead unless you need to support users from the far East, centering content within elements using CSS is dead easy. Three simple rules:

display:        table-cell;
text-align:     center;
vertical-align: middle;

So for instance:

<style>
  .content {
    width: 300px;
    height: 300px;
    border: 1px solid #aaa;
    padding: 2px;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
  }
</style>
<div class="content">
    Here is <strong>my content</strong> with
    <em>markup</em>; my content wraps in the container,
    but that's not a problem for this technique.
</div>

That comes out with the content nicely displayed centered both horizontally and vertically. Unlike the line-height trick, it works well with content that wraps. Here's a live example.

I'm not saying we should have to say things are table-cells when they're not, but at least it's only in the presentation layer, not the markup.

2 comments:

Unknown said...

if i am giving position:absolute, its not working.Could you please explain this?

Unknown said...

Avail the offer and best fitness band under 2000 in india with premium quality
and best Features. Buy now the best fitness band. best fitness band below 2000