Fixing fieldsets
The fieldset
element is a really useful one. It creates a grouping of related form fields, giving them a label in the shape of a legend
element.
Sadly, people have been avoiding the fieldset element. Purely for lack of styling options (or reluctance to add a mess of hacky CSS), this semantically clear and accessibility-enhancing element has been ignored since forever.
The appearance of a fieldset and its associated legend is more or less hardcoded into the browser, and it acts more like replaced content than the simple container and text pairing that it is. The HTML spec has formalized these wierdnesses, and dictates some rather odd behaviors of how the fieldset
and legend
combo is to be rendered:
A fieldset element's rendered legend, if any, is expected to be rendered over the block-start border edge of the fieldset element as a block box (overriding any explicit 'display' value).
I think it's about time that we fix this. I also think that browser makers and spec writers have a unique opportunity to implement that fix at this moment in history.
Enter display: contents
. This declaration basically tells the browser to not generate a rendered box for the element to which it is applied. Currently, it does not work on <code>fieldset</code> elements where supported - but I think it should. When chatting to Jeremy about this, he said it sounded like "a DOCTYPE switch for fieldset rendering", which I think is spot on.
The legacy appearance of fieldsets probably needs to be preserved for compatibility reasons. But display: contents
is not supported in any old browsers, and is most likely used on exactly zero sites using the legacy look of fieldsets. If it is applied, the legend should probably just become an inline element, and it would be up to authors to style it any way they see fit.
So: browser makers should allow authors to set display: contents
on fieldset
elements, thus removing all of the associated weird handling of backgrounds and borders, and weird positioning of legend elements inside them. Should a wrapper element for the fieldset be needed, authors can add a div
or other element. The spec should allow for this exception - I've opened issues against the WHATWG spec as well as the W3C HTML spec, and I hope that's at least a start to get the ball rolling.
Come on, people – let's fix this.
Update: it seems that the CSS Display spec actually has an appendix describing this very situation, and that display: contents
should remove magic display behavior from legend
elements specifically when it is applied. In which case, the spec authors deserve a break, and bugs will have to be opened agains browser implementations instead. Specifically, Chrome (Canary, with experimental web features flag enabled) gets it right on fieldset
but not legend
, and Firefox disregards it completetly. I've put up a quick test on Codepen.