Kirill
Kirill

Reputation: 406

Is it possible to align element's width like in a table with CSS without altering HTML?

I've put together a demo of current menu. It is not feasible to change HTML structure.

HTML

<ul class="menu row1">
    <li>item</li>
    <li>varied item</li>
    <li>item</li>
    <li>item</li>
</ul>
<ul class="menu row2">
    <li>longer item</li>
    <li>item</li>
    <li>longer item</li>
</ul>

CSS

.menu li {
    display: inline-block; border-right: 1px solid; 
    padding: 0 10px; margin: 0; line-height: 32px;
}
.menu {border: 1px solid; margin: 10px 10px 0;}
.menu.row2 {margin-top: 0; border-top: 0;}
.menu li, .menu {border-color: #888;}

JS

var $row0 = $('.menu.row1 > li');
var $row1 = $('.menu.row2 > li');

for (x=0; x < $row0.length; x++) {
    if (typeof $row1[x] != 'undefined') {
        var w1 = $($row0[x]).width();
        var w2 = $($row1[x]).width();
        var w3 = Math.max(w1, w2);

        $($row0[x]).add($row1[x]).width(w3);
    }
}

Is it possible to get same effect as current JS with CSS only? Thanks.

Update:

Thanks to Big00d for answering this. I updated the demo.

New CSS

.menu li {
    display: table-cell; border: 1px solid #888; 
    padding: 0 10px; margin: 0; line-height: 32px;
    border-left: 0;
}
.menu {margin: 10px 10px 0; display: table-row;}
.menu.row2 {margin-top: 0;}
.menu.row2 li {border-top: 0;}

Supported by IE8 and above.

Upvotes: 3

Views: 170

Answers (2)

Maen
Maen

Reputation: 10698

Add display:table-row; on .menu and display:table-cell on .menu > li, this should do the trick

Upvotes: 3

Seimen
Seimen

Reputation: 7250

You probably want to use display: table/table-row/table-cell with vertical-align:bottom;: http://www.quirksmode.org/css/display.html#table

Upvotes: 3

Related Questions