4

I want the container div (#a-container in this example) to fit the width of its children, that are inline-block divs. In this example, I want the #a-container div to be just the size of 2 .a div. Is it possible? (pure CSS please)

#a-container {
  width: 250px;
  background-color: gray;
}
.a {
  background-color:blue;
  width:100px;
  height: 100px;
  display:inline-block;
}
<div id="a-container">
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
</div>
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41
Arnaud
  • 4,884
  • 17
  • 54
  • 85
  • Maybe [this](https://jsfiddle.net/lmgonzalves/r2fzxhf3/1/)? – lmgonzalves Jun 28 '15 at 20:16
  • Why do you want the container to be **smaller** than the total width of it's children? – Paulie_D Jun 28 '15 at 20:26
  • 1
    This question is incorrectly marked as a duplicate. The answers on the supposed duplicated question do not work. [Here's jsfiddle showing the above example with the answer applied from the incorrectly linked duplicate](http://jsfiddle.net/greggman/qbx3kfho/). In particular the question on the other page only has 1 child element. This question has multiple child elements and needs a different answer. – gman Oct 17 '15 at 22:51

1 Answers1

3

Here's a fiddle that uses display: table and floating: http://jsfiddle.net/vqjnoqur/.

HTML:

#a-container {
  display: table;
  background-color: gray;
}

.a {
  background-color:blue;
  width:100px;
  height: 100px;
  margin: 5px;
  float: left;
}

.a:nth-of-type(2n + 1) {
    clear: left;
}
<div id="a-container">
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
</div>
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41
DRD
  • 5,557
  • 14
  • 14
  • Thanks. Is it possible to extend this solution so that it works for any number of divs per row? – Arnaud Jun 28 '15 at 20:16
  • Yeap, just change the formula in the last selector from `2n + 1` to something else: http://jsfiddle.net/25hLhLby/. That's the beauty of `display: table` it shrinkwraps its content while still remaining essentially a block that also does not require clearing of floats. – DRD Jun 28 '15 at 20:19
  • Hi @DRD i want to know more about this **.a:nth-of-type(2n + 1)** can you explain .?? i wan to know the use of it.!!! – Himesh Aadeshara Jul 06 '15 at 04:58