Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to force elements with display: table-cell to stack vertically without using display:block?

As an example take the following unordered list and it's container:

<div class="table-like">
    <ul>
        <li><span>Table-cells</span></li>
        <li><span>play nice</span></li>
        <li><span>automatically</span></li>
        <li><span>with auto-height/width/stretching and of course, vertical alignment..</span></li>
    </ul>
    <ul class="row2">
        <li><span>but</span></li>
        <li><span>do</span></li>
        <li><span>they</span></li>
        <li><span>stack up (vertically)?</span></li>
    </ul>
</div>

With the following CSS:

.table-like {
    display: table;
    font-variant: small-caps;
    width: 100%;
}
.table-like ul { 
    display: table-row;
}
.table-like ul li {
    background-color: #DDD;
    border: 1px solid #FFF;
    display: table-cell;
    overflow: hidden;
    padding: .5em 1em;
    vertical-align: middle;
    width: 25%;
}
.table-like ul li span {
    display: block;
    max-height: 2.1em;
}

Is there no way to force a row to stack vertically while retaining the benefits of the display:table-cell property (auto-height, vertical alignment, etc.)?

like image 397
u353 Avatar asked Feb 12 '23 19:02

u353


1 Answers

The following CSS might be close to what you need:

.table-like {
    font-variant: small-caps;
    width: 100%;
}
.table-like ul { 
}
.table-like ul li {
    background-color: #DDD;
    border: 1px solid #FFF;
    display: table;
    width: 25%;
}
.table-like ul li span {
    padding: 0.5em 1.0em;
    vertical-align: middle;
    display: table-cell;
    height: 2.1em; 
}

If you want the cells to stack vertically, you need to have one table-cell per row, that is how tables work.

What I would do is apply display: table to the li elements, which will force them to be block level and hence start on a separate line.

You can then apply display: table-cell to the li span elements to take advantage of the vertical-align properties and so on.

Note that if you want a max-height within the table-cell, you will need to add an inner wrapper element within the <span> elements and apply a fixed or max-height to an inline-block display type.

Also, for a table-cell, the height value is taken to be a minimum value (min-height will not do anything).

Note that if you have long non-breaking text lines, the table width will expand to accommodate the text, see 4th cell of first ul element. You may need a min-width value on the table li elements depending on your design.

See demo at: http://jsfiddle.net/audetwebdesign/4tZhd/ and image below:

enter image description here

like image 97
Marc Audet Avatar answered Feb 15 '23 09:02

Marc Audet