Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit div width to inline-block children (unknown number of divs per row)

Tags:

I want the container div (#a in this example) to fit the width of its children, that are inline-block divs.

The number of divs per row is unknown, because it depends on the size of the screen.

On the example, what I would like is that there is no extra gray space at the right of the #a container.

Is it possible? (pure CSS please)

#a {      background-color: gray;  }    .b {      width: 110px;      height: 110px;          display: inline-block;      background-color: blue;  }
<div id="a">      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>      <div class="b"></div>  </div>
like image 393
Arnaud Avatar asked Jun 28 '15 20:06

Arnaud


1 Answers

Since there doesn't seem to be a CSS-only method, here's some quick JavaScript to get the job done.

  1. Temporarily change the parent's display style to inline, so that it will shrink-to-fit its content.
  2. Set the parent's width to its shrunk-to-fit width using getBoundingClientRect().
  3. Restore the parent's default display style by clearing it.

Snippet

var a = document.getElementById('a');  a.style.display = 'inline';  a.style.width = a.getBoundingClientRect().width + 'px';  a.style.display = '';
#a {    background-color: gray;  }  .b {    width: 110px;    height: 110px;    display: inline-block;    background-color: blue;  }
<div id="a">    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>    <div class="b"></div>  </div>
like image 176
Rick Hitchcock Avatar answered Oct 18 '22 07:10

Rick Hitchcock