Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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>
like image 817
panthro Avatar asked Apr 15 '15 14:04

panthro


1 Answers

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>
like image 162
Josh Crozier Avatar answered Oct 24 '22 11:10

Josh Crozier