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.

8 comments:

Unknown said...

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

best fitness band under 2000 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

Mihir Mane said...

Apply for gym trainer jobs, freelance graphic designer jobs, freelance make artists jobs, freelance singing jobs, freelance acting jobs in India. modelling jobs

abhikhurana said...

Buy gifts for beer lovers, Christmas gifts for parents, Christmas gifts for grandma, grandpa and for all your dear ones. christmas gifts for parents

sanjupawar said...

Looking for Indian news in hindi? Watch the latest, upcoming, trending, and viral news which are going viral in India. india trending

georgefernandis said...

Get the quotes to share for whatsApp, Facebook status of good morning, good night,
motivational, inspirational, best friendship quotes etc. quotes in hindi

rohit chavan said...

Don't miss the deal to buy the best microwave oven of all time under under 5000, 10000,
15000 in India. best microwave convection oven

Angel17 said...

This is great. Thanks for sharing this information! Porch Screening Port Charlotte, FL