Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sibling divs match height in container

Tags:

I have three divs in a container: http://jsfiddle.net/fBe9y/

One div has a lot of content. How do I get the other two divs, with less content, to match the height of the longest div?

I tried adding height: 100% to all the divs, but it doesn't work because that would need a height on div.container, which I don't know before rendering.

like image 724
atp Avatar asked Oct 03 '12 20:10

atp


People also ask

How do you make two DIVs the same height?

Basically what you do is make both divs/columns very tall by adding a padding-bottom: 100% and then "trick the browser" into thinking they aren't that tall using margin-bottom: -100% .

How do you make two DIVs float the same height?

Answer: Use the CSS3 flexbox With CSS3 flex layout model you can very easily create the equal height columns or <div> elements that are aligned side by side. Just apply the display property with the value flex on the container element and the flex property with the value 1 on child elements.

How is the height of a div determined?

You can use 2 properties, clientHeight and offsetHeight to get the height of the div. clientHeight includes padding of the div. offsetHeight includes padding, scrollBar, and borders of the div.

How do I get the height of an element in CSS?

height() It returns the current height of the element. It does not include the padding, border or margin. It always returns a unit-less pixel value. Note: The height() will always return the content height, regardless of the value of CSS box-sizing property.


1 Answers

I recommend using display: table-row; and display: table-cell; for this. In short, what you do is make a table layout, but using <div> tags, and then style them to behave like a table.

This is better than just using a table for semantic and accessibility reasons.

But generally speaking, CSS does not give you many ways to refer to an element's siblings this way. The <table> tag does, but then it confuses screen readers and things.

If you wanted more rows, you would have more .container <div>s, and then create another <div> wrapping them all, and give it display: table;.

So with the same HTML you had, this CSS does what you want:

.container {     display: table-row; }  .tile {     display: table-cell;     width: 100px;     background: #eee;     border: 1px solid black; }​ 

See Fiddle.

Of note: while display: table; et al. are widely supported, IE did not add support until version 8. If you plan on supporting this for IE 7 or lower, you'll be forced to use a more complicated approach, like @Hristo's.

like image 179
KRyan Avatar answered Dec 30 '22 16:12

KRyan