如何使图例尊重 FIELDSET 宽度

How to make LEGEND respect FIELDSET width

我有一个 fieldset 和一个 legend 可以加载很长的字符串。

我希望 legend 尊重 fieldset 的宽度,只用掉 space 的 50%。

目前,如果 legend 太长,它仍然只占 fieldset 的 50%,但它会迫使 fieldset 像整个一样宽正在显示字符串。

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>

问题似乎与百分比值有关。您会注意到字段集比图例大两倍,因为您使用的是 50%,因此字段集根据图例内容设置其宽度,然后根据该宽度解析百分比宽度。

修复的一个想法是考虑长度而不是百分比,最接近百分比的是vw单位

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>

另一个技巧是将字段集的宽度设置为长度,这样它就不会考虑子内容。为此,我们可以使用较小的值并考虑 min-width:100% 以保持块行为

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>