6

I would like to have a background for a legend field within a fieldset. And I want it to take up the full width, but only within the fieldset. If I use legend {width: 100%} it will be wider than the fieldset.

Here is an example, runnable in JSFiddle:

<html>
<head>
<style>
fieldset {
    border:0;
    outline: 1px solid gray;
}

legend {
    font-weight:bold;
    background: orange;
    width: 100%
}
</style>
</head>
<body>
<fieldset>
    <legend>Legend</legend>
    Content of Fieldset
</fieldset>
</body>
</html>

Is there any way I can make the legend only fill up the width within the fieldset?

Jonas
  • 121,568
  • 97
  • 310
  • 388

2 Answers2

4

See: http://jsfiddle.net/TAvRF/1/

You can use box-sizing: border-box:

legend {
    font-weight:bold;
    background: orange;
    width: 100%;

    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Then you can add padding: http://jsfiddle.net/TAvRF/5/

Although, just setting padding: 0 and forgetting about box-sizing: border-box seems to work for me.. http://jsfiddle.net/TAvRF/6/

thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • Thanks, it was great to be able to use `padding: 5px` in combination. – Jonas Jun 10 '11 at 23:05
  • Good to know it's currently supported with all current major browser versions too, not sure if you want to watch out for the legacy ones: [caniuse.com](http://www.caniuse.com/#search=box-sizing) – Chris Kempen Jun 06 '12 at 08:04
  • What about padding for fieldset contents? – pgreen2 Jan 18 '13 at 15:54
  • @pgreen2 what I generally do is place a `
    ` inside the fieldset with the content. That tag can be padded exactly as expected.
    – Alexis Wilke Jan 07 '14 at 06:00
1

It sounds like a simple padding problem, I think you can easily solve it using a reset or setting the padding in the legend:

legend {
    font-weight:bold;
    background: orange;
    width: 100%;
    margin: 0;       /* added just in case... */
    padding: 0;
}
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • Thanks, this also solved the problem. But when using `box-sizing: border-box;` I was able to use custom padding to. – Jonas Jun 10 '11 at 23:04