How do you get an inline-block element to fit its content width, if the content line-breaks because of screen width?
<!-- parent inline-block -->
<div style='display: inline-block;'>
<div style='display: inline-block; width:200px;'></div>
<!--
If this child line breaks,
two 200px wide blocks are stacked vertically.
That should make the parent width 200px,
but the parent stays much wider than that
-->
<div style='display: inline-block; width:200px;'></div>
</div>
I can't think of how to phrase the question so it sounds easy, but I put together a simple JSFiddle illustrating.
Solution 1
You can't. By default, inline-block elements have a shrink-to-fit width:
The shrink-to-fit width is:
min(max(preferred minimum width, available width), preferred width).
Then,
- When
preferred minimum width <= preferred width <= available width, the width will be thepreferred width, as you desire. - When
available width <= preferred minimum width <= preferred width, the width will be thepreferred minimum width, as you desire. - When
preferred minimum width <= available width <= preferred width, the width will be theavailable width, even if you don't like it.
If you really don't want this, I guess you could add a resize event listener with JS, and set the desired width manually.
Solution 2
inline-block elements can't achieve this layout - as demonstrated by @Oriol - but,
CSS Grid can achieve this layout.
Codepen demo (Be sure to resize)
Basically the relevant code boils down to this:
ul {
display: inline-grid; /* (1) */
grid-template-columns: repeat(auto-fit, 100px); /* 100px = column width - (2) */
min-width: 50vw; /* or any user-defined min-width (3) */
}
Make the container element an inline-grid container. This will cause the grid to 'shrink-wrap' its contents - so that the grid width will never be wider than it's contents.
Set the grid with a responsive layout (The
auto-fill/auto-fitvalue is used for responsive layouts). If there is no room in a row to fit the next item - it wraps to the next row.
When a responsive layout is used together with an inline-grid - the grid width will equal the width of one item of the grid. (when no width/min-width is explicitly set - like this)
- Set the container with a min-width which represents (at most - one partial item less than) the desired maximum width for the container.
So if the given min-width exactly fits in a certain number of items - that means that this will also be the maximum width of the grid because the next item will wrap.
If however the min-width doesn't exactly correspond to the width of 'n' items in that it also fits in part of the n+1th item - in this case the grid will slightly expand to exactly fit the n+1th item - with the n+2th item wrapping to the next row.
