How is it possible to size a <div>
not based on the real content, but based on a non-displayed ghost content?
Example: here the box with content "A" should be sized as if its content was "BCD":
.container { display: flex; width: 10em; }
.item { flex-grow: 1; text-align: center; padding: 0.5rem 1rem;
border: solid black 1px; }
<div class="container">
<div class="item" data-ghost-content="BCD">A</div>
<div class="item">B</div>
<div class="item">C</div>
</div>
Note: the container is a flexbox.
5
Answers
Yes, you can make the additional content
visibility: hidden;
and it will consume space but not be shown:In this approach, the "ghost content" would not include the actual visible content that’s already there in the element, so it’s just "BC".
If you want the result to be centered, you could have "ghost" data attributes for ":before" and ":after".
Not sure if you can adjust your structure a bit?
It depends on how your page is created, manually or with JS. But if you can manage to add an inline style with a
--char-count
custom property you can use theflex
shorthand to get a generic solution:Do not use
flex-grow
as for this solutionflex-basis
actually needs to be0%
The fun part of flexbox is that, when using different
flex-grow
values (asflex
), the mechanism will distribute the available space to ratio using the various definedflex-grow
values.BTW: In CSS var(.., fallback) the fallback value can also be
0
if so required, resulting in flexbox defaultflex-grow: 0
for ‘unset’ items.How about adding a
.wrapper
, like this:…and then, a hidden pseudo-element containing the ghost content. The actual content will be
absolute
-ly positioned so as not to consume any space:To preserve
text-align
ing, make.item
flexboxes:Try it:
On the assumption that you’re able to adjust the HTML, to include a
<span>
tag for the visible content, then I’d suggest using CSS grid, as this allows elements to be stacked "on top of" each other, in the space from background to foreground, as follows (with explanatory comments in the code):JS Fiddle demo.
References:
content
.display
.grid-column
.grid-row
.place-content
.user-select
.visibility
.z-index
.