November 6, 2012

Why is "display: table-cell" messing up my div's?

Question by eric01

I’m trying to center the strings “1”,”2″ and “3” vertically as seen here:

But when I use display: table-cell; vertical-align: middle; for all 3 div’s, but then I get his unwanted result:

HTML is

<div id='alldivs'>
    <div id='red' class='each_div'>1</div>
    <div id='blue' class='each_div'>2</div>
    <div id='green' class='each_div'>3</div>

</div>

CSS is

.each_div { 
     width: 80px;
     height: 50px; 
     text-align: center;
     display: table-cell; vertical-align: middle;
}

Demo

How do I keep the 3 div’s aligned vertically while keeping vertical alignment within each div?

Answer by Starx

This is a conceptual misunderstanding. Without a parent element with display:table-row the tables cell will always span over full width, because it will create anonymous table object of table-row and table.

According to W3C Specification article: Tables

Document languages other than HTML may not contain all the elements in the CSS 2.1 table model. In these cases, the “missing” elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself, consisting of at least three nested objects corresponding to a ‘table’/’inline-table’ element, a ‘table-row’ element, and a ‘table-cell’ element. …..

Here is a quirksmode page showing uses of display: table and so on. A image showing the same effect as on this question.

To solve this problem semantically, you have to add an extra element to display as row.

<div id='alldivs'>
    <div id='red' class='each_div'>
        <div class="cell">1</div>
    </div>
    <div id='blue' class='each_div'>
        <div class="cell">2</div>
    </div>
    <div id='green' class='each_div'>
        <div class="cell">3</div>
    </div>
</div>

Then assign relative CSS to them

#alldivs { display: table; }

.each_div {
     display: table-row;
}

.cell {     
    width: 80px;
    height: 50px;
    display: table-cell;
    vertical-align: middle;
    border: 1px #000 solid;
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!