See this: http://jsfiddle.net/90d7144p/
I want the width of the DIV with class rect
be as long as its underlying DIVs with class box
. Class box
should not be changed (at least minimum changes). Also, the boxes are not aligned by tables. I don't care for the size of the container (black border).
This
should be
CSS:
* { margin: 2px; }
.container { width: 100%; border: 1px solid black; }
.box { display: inline-block; width:100px; height:100px; border: 1px solid red; }
.rect { border: 1px solid green; }
HTML:
<div class="container">
<div class="rect">The width must be as long as underlying boxes.</div>
<div class="box">BOX</div> <div class="box">BOX</div>
<div class="box">BOX</div> <div class="box">BOX</div>
<div class="box">BOX</div> <div class="box">BOX</div>
<div class="box">BOX</div> <div class="box">BOX</div>
<div class="box">BOX</div>
</div>
Is there any CSS or HTML based solution?
You could use media queries, to specify the width of rect each time a box collapses to the next line. This involves calculating each break point and aply a media query to it.
To make calculations easier, you should use floats so that the white-space between elements doesn't ruin your layout.
The following demo needs tweaking but it should show you what I am talking about :
DEMO (resize the result window above 650px wide to see it works)
CSS example:
@media screen and (min-width: 742px) and (max-width: 847px){
.rect {
width: 736px;
}
}
Here is a solution based on my comment above, it uses media queries:
Since the boxes are fixed width, it is possible to pre-determine how many boxes fit one one line if the screen is [x0, x1] pixels wide. You can feed this information to CSS media queries to create several rules, each one specifies the width of the box for a given range of widths. Here is an example (generated using excel):
.rect { width: 100px; }
@media screen and (min-width: 214px) { .rect { width: 206px; } }
@media screen and (min-width: 320px) { .rect { width: 312px; } }
@media screen and (min-width: 426px) { .rect { width: 418px; } }
@media screen and (min-width: 532px) { .rect { width: 524px; } }
@media screen and (min-width: 638px) { .rect { width: 630px; } }
@media screen and (min-width: 744px) { .rect { width: 736px; } }
@media screen and (min-width: 850px) { .rect { width: 842px; } }
@media screen and (min-width: 956px) { .rect { width: 948px; } }
Code, Demo
Notes:
min-width
is the width of screen, not that of container. 2px were added to compensate for black border.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With