pgreen2
pgreen2

Reputation: 3651

How to make legend extend full width of fieldset and maintain content padding?

My goal is to render fieldsets with a border and the legend to be located at the top with a background color. The background color of the legend should extend to the full width of the fieldset.

Based on Make a legend fill up the full width within the fieldset, I started with the following jsfiddle: http://jsfiddle.net/pdgreen/wcYXX/0.

It looks good, but fieldset has no padding, so the form elements are too close to the borders. When I add in the padding, I am left with: http://jsfiddle.net/pdgreen/wcYXX/1/.

The content looks fine, but the title not longer extends the the width of the fieldset.

If I surround the content with a div, I can add in the padding: http://jsfiddle.net/pdgreen/wcYXX/2/, however that requires the additional div.

Is there a way to make it look like the third fiddle, without the extra div?

Upvotes: 3

Views: 4797

Answers (1)

Pevara
Pevara

Reputation: 14310

Yes, by counteracting the padding of the fieldset with negative margin on the legend. Something like this: http://jsfiddle.net/wcYXX/3/

I set the margin of the fieldset to -5px (the same as the padding of the fieldset, but negative) and then added 5px padding to put the text back where it belongs.

This also means you no longer need the border-box, which is not well supported in legacy browsers.

The fieldset css now looks like this:

fieldset legend {
    background: #369;
    color: #FFF;
    font-weight: 700;
    text-align: left;
    white-space:nowrap;

    margin: -5px;
    padding: 5px;
    display: block;
    width: 100%;

}

Upvotes: 5

Related Questions