Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I start new row of CSS table cells without a row wrapper element?

Tags:

Given markup like this:

<div class="a">A</div>
<div class="b">B</div>
<div class="a">A</div>
<div class="b">B</div>
<div class="a">A</div>
<div class="b">B</div>

Is it possible to style this document to look like this:

|-------|---------|
|       |         |
|   A   |    B    |
|       |         |
|-------|---------|
|       |         |
|   A   |    B    |
|       |         |
|-------|---------|
|       |         |
|   A   |    B    |
|       |         |
|-------|---------|

(and if the content in A or B is longer, its neighbor will grow to match its height)…

without any additional markup?

I understand that giving .a and .b a display value of table-cell would just make this one big row.

What’s the solution?

like image 236
Alan H. Avatar asked Jun 04 '12 22:06

Alan H.


People also ask

Can you wrap a table row in a div?

You should not be doing that... is not a valid HTMl markup... Rows can not be wraped by divs.

How do I create a div row?

To create rows, add a div with a class=“row” that encases the column code. Rows must always be placed inside of a container. Rows span the width of the container. They have a negative 15 pixel margin at the end, essentially removing the 15 pixel margin set by its container.


2 Answers

Not without flexbox, which hasn’t landed in several major browsers yet, seems to be the consensus.

like image 106
Alan H. Avatar answered Sep 23 '22 02:09

Alan H.


No, I think it's not possible "without any additional markup". It needs:

  • div wrapper with display: table-row; containing A anb B "cells"
  • JavaScript with listeners on divs, which will determine max of A anb B's heights in each pair and set it to smaller one

Solution for second one:

CSS:

.a, .b {
    padding: 0.5em;
    float: left;
}
.a:nth-child(n+1) {
    clear: both;
}

jQuery:

$(function() {
    var max_width_a = 0, max_width_b = 0;
    $("div.a").each(function() {
        var elem_a = $(this),
            elem_b = elem_a.next("div.b"),
            height_a = elem_a.height(),
            height_b = elem_b.height(),
            pair = [elem_a, elem_b];

        max_width_a = Math.max(max_width_a, elem_a.width());    
        max_width_b = Math.max(max_width_b, elem_b.width());  
        $(pair).height(Math.max(height_a, height_b));
    }).width(max_width_a);
    $("div.b").width(max_width_b);
});

I've updated your Fiddle. Works on document ready, you have to customize it if you want to determine dynamic height changes.

Let me know if I have to explain how it works. Of course you can coerce div.a and div.b's width in CSS and don't check for max width with jQuery (then you will have to determine only max height in each pair).

like image 31
Wirone Avatar answered Sep 23 '22 02:09

Wirone