Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cross-browser form `fieldset` content height in % (with legend)

I want to set in % the height of a div included in a fieldset, but browsers don't calculate the same way the inside height of the fieldset when you use legend !

Firefox: height: 100% consider the height of the legend: it's ok.
enter image description here

Chrome: height: 100% does NOT consider the height of the legend: it overflows.
enter image description here

Internet Explorer: height: 100% does NOT consider the height of the legend: it overflows.
enter image description here

1. Do you know a clean solution to have the same result in the 3 browsers?

2. Which is right compared to W3C recommendations?

Here is the code used to make the test:

<html>
<body>
  <fieldset style="height:60px;width:150px;">
    <legend>Legend</legend>
    <div style="height:100%;width:100%;margin:0;padding:0;background-color:#FF0000;">
DIV : height 100%
    </div>
  </fieldset>
</body>
</html>
like image 783
M Denis Avatar asked Nov 10 '22 14:11

M Denis


1 Answers

This is an interesting case.
To your 2nd question: It might arise out of W3C HTML5 standard spec being very vague of the visual representation of <legend> element. There has been a long history of browser inconsistencies around <legend>.

To answer your question 1. and come up with a cross-browser consistent position of legend:
In order to get the miscalculation resolved, you have to remove legend from the content flow, for example by adding float to it. Then you need to reposition it relatively and 456bereastreet.com came up with a sibling selector clearing the float immediately after.

Demo:
https://codepen.io/Volker_E/full/zqPjrK/

CSS code on top of your inline styles:

fieldset {
  position: relative;
  margin: 0;
  border: 1px solid #000;
  padding: 0;
}
legend {
  float: left;
  margin-top: -1em;
  line-height: 1em;
}
legend + * { /* @link: http://www.456bereastreet.com/archive/201302/fieldset_legend_border-radius_and_box-shadow/ */
  clear: both;
}

It is indeed browser differences (bugs?) or vague spec, which don't allow to style it consistently without taking legend out of flow.

like image 195
Volker E. Avatar answered Nov 15 '22 06:11

Volker E.