Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

css - Sibling divs match height in container

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...