Search code examples
htmlcssalignmentcss-tables

Make text in table cells independent of each other


I have a set of nested divs displayed as a table like this:

<div class="table">
    <div class="table-row">
        <div class="table-cell"><div class="just-a-box"><!--&nbsp;--></div></div>
        <div class="table-cell">Just some text</div>
    </div>
</div>

Table display is achieved using CSS. The "just-a-box" div in the first cell is styled as follows:

.just-a-box {
    background-color: blue;
    height: 50px;
    width: 50px;
}

My problem is that this box affects the positioning of the text in the second column unless I add a " " inside the box as indicated by the HTML comment. The text is not aligned at the top of the cell anymore.

I don't understand why this is happening. I am looking for a solution to make the content of the second cell completely independent of the first cell since I do not want to make any assumptions regarding the first cell's content. Is this possible?

Any hints appreciated! It would be awesome if someone could also explain why the cells are not independent from each other anyway. That's what I would have expected.

See http://jsfiddle.net/fMWQH/1/ for an illustration of the problem.


Solution

  • the table cells have a default vertical alignment of baseline.

    the empty box in your example has no content, so the baseline for this box is its bottom edge. the text in the other table cell then aligns itself to this baseline. when you add some text in the blue box the baseline changes which makes it appear as if the content is now top aligned.

    as already mentioned in other answers you can change the vertical alignment for all cells to top or make sure you don't have empty cells and keep the baseline setting.