Whether your page is built manually or with JS will determine the approach you need to take. If you can incorporate an inline style using a custom property like --char-count
, you can utilize the flex
shorthand for a more versatile solution:
.item { flex: var(--char-count, 1) } /* falls back to: 1 1 0% */
Avoid using flex-grow
in this case, as the desired outcome requires setting the flex-basis
specifically to 0%
.
One interesting aspect of flexbox is that by adjusting flex-grow
values (as seen in the use of flex
), the space available will be allocated based on the ratio determined by these values.
Additionally, when utilizing CSS var(.., fallback), the fallback value can also be set to 0
if needed, leading to the default flexbox behavior of flex-grow: 0
for 'unset' items.
.container {
display: flex;
width: 10em;
}
.item {
flex: var(--char-count, 1); /* defaults to 1 if 'unset' */
text-align: center;
padding: 0.5rem 1rem;
border: solid black 1px;
}
<div class="container">
<div class="item" data-ghost-content="BCD" style="--char-count: 3">A</div>
<div class="item">B</div>
<div class="item">C</div>
</div>