Centering the text of a legend element with CSS

Centering the text of a legend element with CSS is not so simple as it could seem at first glance. The main problem that we have to face is that this kind of element is governed by the internal rules of the browser, because CSS specifications don't say how this element should be handled and rendered. The result is that every browser has its own rules, so that we have to use some workarounds to manage this situation. I hate to use presentational markup, but in this case I actually ended up with a basic markup like this:

<form action="" method="post">

<fieldset>

<legend><span>Test</span></legend>

<div class="checkbox-container">
<input type="checkbox" id="check1" name="check1" />
<input type="checkbox" id="check2" name="check2" />
</div>

</fieldset>

</form>

However, all the presentational markup can actually be generated by JavaScript and here has only a demonstrative purpose. Then come our CSS styles:

form {

    margin: 0;
    padding: 0;
    height: 100%;

}

fieldset {

    margin: 0;
    padding: 0;
    border: 1px dashed #000;
    border-width: 0 0 1px 0;

}

legend {

    margin: 0;
    padding: 0;
    text-align: center !important;
    display: block !important;
    width: 100%;
}

legend span {

    background: #fff;
    position: relative;
    top: 0.7em;
    padding: 0 0.5em;

}




.checkbox-container {

    border-top: 1px dashed;
    width: 100%;

}

Here we've turned our legend element into a block-level element and we've assigned a width to it (100% is required to make it work) plus the declaration text-align: center. Finally, we've stylized our extra span element by adding some horizontal padding and relative positioning plus a background color which is equal to the background color of the page (it's necessary to create the effect of the hanging text). Notice that we've actually used the top border of our checkbox wrapper instead of the top border of the fieldset element just because this approach would cause some problems. You can see this demo here.

Screenshots taken from Internet Explorer

IE 6

IE 6

IE 7

IE 7

IE 8

IE 8

2 thoughts on “Centering the text of a legend element with CSS”

  1. I think your example at http://tjkdesign.com/articles/how_to_position_the_legend_element.asp is much better. I mean that the span element would have been inserted and created via JS.

Leave a Reply

Note: Only a member of this blog may post a comment.