简体   繁体   中英

Prevent the fieldset element's border from going through the legend element

I have a fieldset, how can I position the legend inside a fieldset with a border? I want the border to go around the legend and not through the middle of it.

JSFiddle

 fieldset { border: 0; padding: 0!important; margin: 0; min-width: 0; border: 1px solid red; } legend { padding: 0!important; } 
 <fieldset> <legend>Title</legend> </fieldset> 

One option would be to float the legend element to the left:

 fieldset { border: 2px solid #f00; } legend { float: left; width: 100%; padding: 0; font-weight: bold; } 
 <fieldset> <legend>This is a legend</legend> <label>Here is an input element: <input type="text" /></label> </fieldset> 


Another approach would be to use an outline rather than a border :

 fieldset { border: none; outline: 2px solid #f00; } legend { padding: 0.6em 0 0; font-weight: bold; } 
 <fieldset> <legend>This is a legend</legend> <label>Here is an input element: <input type="text" /></label> </fieldset> 


Another approach would be to absolutely position the legend element relative to the parent fieldset element. This is probably the least flexible approach.

 fieldset { border: 2px solid #f00; position: relative; padding-top: 2.6em; /* Displace the absolutely positioned legend */ } legend { position: absolute; top: 0; left: 0; padding: 12px; font-weight: bold; } 
 <fieldset> <legend>This is a legend</legend> <label>Here is an input element: <input type="text" /></label> </fieldset> 

A variation on the accepted answer (using SASS) which should work in all modern browsers (IE9+)

fieldset {
  > legend {
    float: left;

    + * {
      clear: both;
    }
  }
}

This will clear the next element after the float so you don't have to worry about your layout being messed up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM