ant45de ant45de - 6 months ago 14
HTML Question

div takes more width then needed when elements floated

I have the following html structure:

<div class="container">
<div class="square_container">
<div class="square">
box1
</div>
<div class="square">
box2
</div>
<div class="square">
box3
</div>
<div class="square">
box4
</div>
<div class="square">
box5
</div>
</div>
</div>


This is my CSS:

.square_container{
display:inline-block;
}
.square{
background-color:red;
height:150px;
width:150px;
float: left;
margin:20px;
}


The container-class is the bootstrap container.
This is a screenshot of how it looks on a large screen:

enter image description here
The squares are in a line and they are centered (just like i want it)

So now I am making the browser window smaller and this is what happens:



The squares are floating, thats why the 4th square is breaking to a new line.
But they are not centered anymore...
The
square_container
is wider than it should as you can see on the 2nd picture.
So I tried to clear after the the third manually. Then the
square_container
took only the width it needed and was centered again.

My question is: Can clear dynamically? I don't know at which element its breaking. Is there another solution where my
square_container
is just as wide as the elements inside?

Thanks for your help!

Answer

edit As commented below, I think this might be what you are looking for, I used media queries to set the box width, see fiddle: https://jsfiddle.net/5roaxfsj/1/

.square_container{
    display:inline-block;
    width: 950px;
    background-color: lightblue;
}
.square{
    background-color:red;
    height:150px;
    width:150px;
    float: left;
    margin:20px;
}
@media (max-width: 950px){
  .square_container{width: 760px}
}
@media (max-width: 760px){
  .square_container{width: 570px}
}
@media (max-width: 570px){
  .square_container{width: 380px}
}
@media (max-width: 380px){
  .square_container{width: 190px}
}

Use flex and center, that way when window gets smaller it automatically distributes the spacing between the boxes, see fiddle: https://jsfiddle.net/c259LrpL/21/

.square_container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  flex-wrap: wrap;
}

.square {
  background-color: red;
  height: 150px;
  width: 150px;
  margin: 20px;
}
Comments