How to get rid of the empty space to the right of the container with floating elements?

When I use float itens inside a container, for example:

Code ( http://jsfiddle.net/tombrito/gx7kL330/7/ ):

.container { background: blue; position: absolute; width: auto; } .floating-box { float: left; width: 150px; height: 75px; margin: 10px; border: 3px solid #73AD21; } 
 <div class="container"> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> <div class="floating-box">Floating box</div> </div> 

... if I resize the window, I see that the width: auto container is not exactly the width of the content:

enter image description here

There is an empty space on the right side. Is there a way to make the container really wide as floating children, even when I resize it?

+2
source share
2 answers

You can use flexbox rules. ( source )

HTML:

 <ul class="flex-container"> <li class="flex-item">1</li> <li class="flex-item">2</li> <li class="flex-item">3</li> <li class="flex-item">4</li> <li class="flex-item">5</li> <li class="flex-item">6</li> </ul> 

CSS

 .flex-container { padding: 0; margin: 0; list-style: none; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-flex-flow: row wrap; justify-content: space-around; } .flex-item { background: red; padding: 5px; width: 200px; height: 150px; margin-top: 10px; line-height: 150px; } 
0
source

If jQuery is an option, I would do something like this:

 $('body').on('resize', function () { var width = document.documentElement.clientWidth || window.innerWidth, itemWidth = 150 + 20 + 6; //width + margin + border, count = Math.floor(width / itemWidth), containerWidth = itemWidth * count; $('.container').css('width', containerWidth + 'px'); }); 

// warning unverified code

0
source

Source: https://habr.com/ru/post/1499323/


All Articles