How to center the <legend> element - what to use instead of align:center attribute?

Assuming your markup looks something similar to this:

<form>
<fieldset>
<legend>Person:</legend>
Name: <input type="text" size="30" /><br />
Email: <input type="text" size="30" /><br />
Date of birth: <input type="text" size="10" />
</fieldset>
</form>

Your CSS should look something like this:

legend {
    margin:0 auto;
}

that's easiest

Oh Dear... You have chosen probably the most difficult thing in CSS when it comes to cross-browser compatibility. Cameron Adams said it best

Probably the only difficulty in styling semantic forms is the legend tag. It is insufferably variable across browsers. In Mozilla, the legend tag is not left-indented from the body of the fieldset, in IE and Opera it is. In Mozilla, the legend tag is positioned in between the fieldset's border and its content, in IE and Opera it is positioned inside the content. This makes it very hard to move the legend inside the fieldset border, or position it flush to the left of the fieldset, as you get varying effects across browsers

You can read more about what he said at Fancy Form Design Using CSS on how to style forms.

My solution to the problem would be to remove the fieldset border completely and absolutely position the legend element. The problem with what you want to do is that it is different in every browser.


The legend can be styled by html attribute quite easily. I've found by searching..

<legend align="center">Legend</legend>

Legends are notoriously resistant to styling.

One thing you can do is use a heading element instead of legend as that will be much easier to style. This does what you want in FF3 and Safari at least.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
h3{
background-color:#FFF;
margin: -1em auto 0;
text-align:center;
width:10%;}
</style>
</head>
<body>

 <form>
<fieldset>
<h3>Person:</h3>
Name: <input type="text" size="30" /><br />
Email: <input type="text" size="30" /><br />
Date of birth: <input type="text" size="10" />
</fieldset>
</form>

</body>
</html>

Tags:

Html

Css