3

I have a container div with multiple floating elements in it. I am trying to make the container width fit the content. I now have a jsFiddle that initially fits the container to the content:

Correct fit

However, as soon as the screen width becomes smaller and the content divs have no space to be displayed on the same line, this happens:

Wrong fit

This is my code:

.container {

  border: 1px solid red;

  display: table;

}

.content {

  border: 1px solid blue;

  width: 100px;

  height: 100px;

  float: left;

}
<div class="container">
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div style="clear:both"></div>
</div>
What should happen is that when the 3rd content div goes to the next row, the container div should become smaller to fit the content. How can i make the container width to fit the content in all cases?

Edit to clarify: The child-divs are behaving correctly. This question is only about changing the width of the container.

user4493177
  • 750
  • 11
  • 32
  • This is not possible with CSS...that's not the way the line-box model works. You'd need to use media queries or javascript. – Paulie_D Jun 18 '16 at 15:20

2 Answers2

1

You can change the container width based on screen size using media query. .container in normal takes width equal to children width, and each children takes width: 102px (width + border left/right) , .container width = children width + container border;

When the screen get width smaller than .container width then, it will push the last element below. from this point you can set media query based on .container width.

https://jsfiddle.net/v5czL9he/2/

* {
  margin:0;
  padding: 0;
}

.container {
  border: 1px solid red;
  display: table;
}

.content {
  border: 1px solid blue;
  width: 100px;
  height: 100px;
  float: left;
}

/* if screen width < .container width
   decrease last element from fisrt row
   decrease it's width from the container width
*/
@media only screen and ( max-width: 308px ) {
 .container {
   width: calc( 306px - 102px );
 }
}

@media only screen and ( max-width: 206px ) {
 .container {
   width: calc( 204px - 102px );
 }
}
<div class="container">
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div style="clear:both"></div>
</div>
0

By adding fixed width? (if I understand correctly what you want)

width:305px;
Andrejs
  • 10,803
  • 4
  • 43
  • 48
  • Fixed width is not possible. The container div should have the smallest width possible, based on the divs inside. – user4493177 Jun 18 '16 at 14:33