Can any HTML element be styled as a fieldset/legend?

Jakob picture Jakob · Jul 17, 2010 · Viewed 10k times · Source

Using the display property, HTML elements become interchangeable from a styling perspective. This doesn't seem to be the case for fieldset and legend, however.

Is it possible to style other HTML elements to look like fieldset and legend?

Answer

joelpittet picture joelpittet · Jul 18, 2010

This works pretty good, but ie6 will act a bit strange if the background is an image, nothing a conditional comment couldn't fix. Tested in IE6-8, FF3.6, Safari 5, Chrome 5

.fieldset {
    position: relative;
    border: 1px solid #000;
    margin: 20px;
    padding: 20px;
    text-align: left;
}

.fieldset .legend {
    background: #fff;
    height: 1px;
    position: absolute;
    top: -1px;
    padding: 0 20px;
    color: #000;
    overflow: visible;
}

.fieldset .legend span {
    top: -0.5em;
    position: relative;
    vertical-align: middle;
    display: inline-block;
    overflow: visible;
}


   <div class="fieldset">
      <div class="legend">
         <span>This is the title</span>
      </div>
      Test
   </div>