I'm curious if there is a way to set the width
property for multiple <span>
elements to the same value if they are not siblings to each other. The width should be based on the largest
span element.
The expected result would be something like a table where the left text will automatically grow.
So instead of this:
Text: Value
Larger Text: Value
I want it like this:
Text: Value
Larger Text: Value
I know this can be done with JavaScript (see example at the end), but I want to know if this is possible with CSS only.
And at best without changing the HTML structure, but I'm open for such an answer as well.
Some similar questions I've found, but they are about direct sibling spans. So it's not really fitting in my case:
Make adjacent sibling elements same width using only CSS
How can I make multiple spans equal width within a div
Why I want a CSS only solution and no JS?
Because I have to loop those elements twice:
- To determine which of those elements is the largest and get the width from it
- To set all elements the same width
Here is the working example with JS:
const variantNames = document.querySelectorAll('.variant-name');
let greatestWidth = 0;
variantNames.forEach( (name) =>
{
if(name.offsetWidth > greatestWidth)
{
greatestWidth = name.offsetWidth;
}
});
variantNames.forEach( (name) =>
{
name.style.width = greatestWidth + 'px';
});
.container,
.variant {
width: 100%;
}
.variant-name {
display: inline-block;
margin-right: 5px;
}
<div class="container">
<div class="variant">
<span class="variant-name">Size:</span>
<span>28</span>
</div>
<div class="variant">
<span class="variant-name">Waterproof:</span>
<span>Yes</span>
</div>
<div class="variant">
<span class="variant-name">Color:</span>
<span>Azure</span>
</div>
</div>