Reputation: 3983
I have a fieldset
with a legend
that may be loaded with a very long string.
I want the legend
to respect the width of the fieldset
and use up only 50% of the space.
Currently, if the legend
is too long it will still only take up 50% of the fieldset
but it will force the fieldset
to be as wide as if the entire string was being displayed.
fieldset {
box-sizing: border-box;
display: inline-block;
width: 100%;
}
legend {
max-width: 50%;
}
/* Oversized SPAN content forces the FIELDSET to exceed the 100% width and breaks the layout. */
legend span {
display: inline-block;
width: calc(100% - 100px);
overflow: hidden;
text-overflow: ellipsis;
vertical-align: middle;
}
<div>
<fieldset>
<legend>Product (<span>WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW</span>)</legend>
</fieldset>
</div>
Upvotes: 6
Views: 1479
Reputation: 273649
The issue seems to be related to the percentage values. You can notice that the fieldset is twice bigger that the legend because you are using 50%
so the fieldset is setting its width based on the legend content then the percentage width is resolved against that width.
One idea of fix is to consider length instead of percentage and the closest one to percentage is vw
unit
legend {
max-width: 50vw;
}
/* Oversized SPAN content forces the FIELDSET to exceed the 100% width and breaks the layout. */
legend span {
display: inline-block;
width: calc(100% - 100px);
overflow: hidden;
text-overflow: ellipsis;
vertical-align: middle;
}
<div>
<fieldset>
<legend>Product (<span>WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW</span>)</legend>
</fieldset>
</div>
Another trick is to make the width of the fieldset a length so it doesn't consider the child content. For this we can use a small value and consider min-width:100%
to keep the block behavior
fieldset {
display:inline-block;
/* this will do the magic */
width:0;
min-width:100%;
/**/
box-sizing: border-box;
}
legend {
max-width: 50%;
}
/* Oversized SPAN content forces the FIELDSET to exceed the 100% width and breaks the layout. */
legend span {
display: inline-block;
width: calc(100% - 100px);
overflow: hidden;
text-overflow: ellipsis;
vertical-align: middle;
}
<div>
<fieldset>
<legend>Product (<span>WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW</span>)</legend>
</fieldset>
</div>
Upvotes: 2