I have a centered box containing a number of elements to be displayed side-by-side, possibly wrapping onto several lines. On resize, I'd like the box to shrink. The elements should remain the same size, wrapping onto additional lines as necessary.
I can think of a few ways of handling this (e.g., setting children to display: inline-block
or float: left
, or setting parent to display: flex; flex-flow: row wrap;
).
In every scenario, resizing causes the elements to wrap. However, this leaves a gap between the last element on the line and the edge of the parent. This behavior is entirely reasonable in most contexts, but here it pulls the elements visually out-of-center.
I'd love it if I could apply some CSS magic to have the parent box "shrink" to the width actually occupied by child elements, ignoring end-of-line space. I was hoping display: table
would come to my rescue here, but no such luck.
I recognize that a workaround would be to use a flex box, specifying justify-content: space-between
(or without a flex box, just text-align: justify
). This would eliminate the gap by distributing unused space between the elements - but I don't really want to have spaces between the items.
Here are some images depicting the issue: before resize / after resize
See below for snippet (I believe you'll need to run it full-page to have it respond to resize).
body {
padding: 50px;
background: pink;
}
.outer {
display: flex;
flex-flow: row wrap;
max-width: 600px;
margin: 0 auto;
padding: 10px;
background: yellow;
}
.item {
width: 100px;
height: 100px;
}
.a {
background: green;
}
.b {
background: blue;
}
<body>
<div class="outer">
<div class="item a"></div>
<div class="item b"></div>
<div class="item a"></div>
<div class="item b"></div>
<div class="item a"></div>
<div class="item b"></div>
</div>
</body>