text-align:center won't work with form <label> tag (?)

HtmlCss

Html Problem Overview


I was going through a site I have just completed, and fixing up some accessibility issues. I had a form:

<input type="hidden" name="redirect" value="thank-you.php" />
<p>Enter your Email Address to receive our Weekly Newsletter</p> 							
<input name="email" type="text" id="formifemail" size="21" />
<input type="image" src="images/newsletter_button.jpg" alt="submit button" border="0" name="Submit" id="Submit" value="Send" />

This was flagged because their is no

tag to a

<input type="hidden" name="redirect" value="thank-you.php" />
<label for="formifemail">Enter your Email Address to receive our Weekly Research</label> 							
<input name="email" type="text" id="formifemail" size="21" />
<input type="image" src="images/newsletter_button.jpg" alt="submit button" border="0" name="Submit" id="Submit" value="Send" />

and the CSS:

#formItem label {
	text-align:center;
	line-height:150%;
	font-size:.85em;
}

But the text appears as left justified, and not centered. I've looked around that there are no obvious bugs. This is happening in both FF 3.x and IE 7.x

Html Solutions


Solution 1 - Html

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Solution 2 - Html

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionedzillionView Question on Stackoverflow
Solution 1 - HtmlCan Berk GüderView Answer on Stackoverflow
Solution 2 - HtmlAndrew HareView Answer on Stackoverflow