When there is free space in the container, the browser increases the width of the elements to fill it.
I need the opposite behavior, so that the browser shrinks the width of the elements enough to make room for the next element.
I know how to do this with JS, but I would like a pure CSS solution.
I’ve dropped the JS code below so you can see what I mean.
function resizeLayout() {
var item_max_size = 200;
var container = document.getElementsByClassName('container')[0];
var container_width = container.getBoundingClientRect()['width'];
var items_need = Math.ceil(container_width / item_max_size);
var new_width = container_width / items_need + 'px';
var items = container.getElementsByClassName('item');
for (const node of items) {
node.style.width = new_width;
}
}
window.addEventListener('resize', function(e) {
resizeLayout();
});
window.addEventListener('load', function(e) {
resizeLayout();
});
html {
height: 100%;
}
body {
margin: 0px;
width: 100%;
height: 100%;
}
.container {
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
background: yellow;
}
.item {
background: green;
border: 2px black dashed;
box-sizing: border-box;
width: 200px;
height: 200px;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
2
Answers
You can achieve your desired results by adding
width
inpercentage
toitem
.check this codepen link I have added example. If I am missing something or misunderstood your question do let me know.
You can use the CSS flex property combined with flex-basis, flex-grow, and flex-shrink.
Flex Property (flex: 1 1 200px;):
This CSS will ensure that the items start with a width of 200px but will shrink to fit into the container without wrapping when there is not enough space.