开发者

Set width of element to combined width of siblings?

开发者 https://www.devze.com 2023-03-19 20:24 出处:网络
Three elements are inside a fluid container in the following configuration: +-----------------+ +-----+ +-----+ |

Three elements are inside a fluid container in the following configuration:

+-----------------+
| +-----+ +-----+ |
| |  A  | |  B  | |
| +-----+ +-----+ |
| +---开发者_运维百科----------+ |
| |      C      | |
| +-------------+ |
+-----------------+

The width of elements A and B is 50%. The width of element C is 100%. You can see a live example here.

The right edges of the rows do not align when the width of the container is an odd number of pixels, due to rounding when computing the width of elements A and B. You can watch the edges misalign and realign while resizing the frame. The effect is exacerbated when the top row contains many more than two elements, say ten.

Instead, I would like the width of element C to be equal to the combined actual width of elements A and B, rather than the combined percentage width. Is this possible without using JavaScript or resorting to a table?


One solution would be to make the first element float left, giving it the desired width. The right one would not float, and have a default width, allowing it to stretch, filling the space left by the left. See a modification of your example for how it might work: http://jsfiddle.net/QDVeD/12/. The basics can be summed up with:

#left {
  float: left;
  width: 50%;
  height: 50px;
}
#right {
  height: 50px;
}

This wouldn't scale as well as you might like for more items than two, though. The last element will usually be slightly longer than the others: http://jsfiddle.net/QDVeD/18/.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号