Placing a fieldset's legend within the border
I was trying to implement a layout where the
<legend> was positioned within the border of its parent
By default browsers will place the
<legend> element on top of the
<fieldset> block-start (i.e. top) border.
Here's a basic example of the markup for a fieldset with a legend and a single checkbox:
<label><input type="checkbox">Option 1</label>
This will be rendered as below. The background color of the legend is set to pink to for illustrative purpose.
Current versions of Firefox and Google Chrome (107 and 108) don't expose the mechanism for this in their user-agent style sheets. I.e. there's no negative
margin-top on the
<legend>, as I would have expected. This behavior appears to be hard wired into browsers and is also explicitly described in the HTML spec.
The trick is to set
float: left on the
<legend> element. This will cause the
<legend> to be rendered like it was an inline element without any allures.
<legend> shouldn't be shown inline, one might either set its next sibling to display as block element or use a flex layout for the entire fieldset:
This article has been published on on my blog. Here's a list of all articles if you're interested in this kind of stuff.
If you have feedback, questions, or want to comment on this, please send me an e-mail or contact me through any other channel.