views:

4858

answers:

3

I use css style text-align to align contents inside a container in HTML. This works fine while the content is text or the browser is IE. But otherwise it does not work.

Also as the name suggests it is used basically to align text. The align property has been deprecated long back.

Is there any other way to align contents in html?

+8  A: 

text-align aligns text and other inline content. It doesn't align block element children.

To do that, you want to give the element you want aligned a width, with ‘auto’ left and right margins. This is the standards-compliant way that works everywhere except IE5.x.

<div style="width: 50%; margin: 0 auto;">Hello</div>

For this to work in IE6, you need to make sure Standards Mode is on by using a suitable DOCTYPE.

If you really need to support IE5/Quirks Mode, which these days you shouldn't really, it is possible to combine the two different approaches to centering:

<div style="text-align: center">
    <div style="width: 50%; margin: 0 auto; text-align: left">Hello</div>
</div>

(Obviously, styles are best put inside a stylesheet, but the inline version is illustrative.)

bobince
If you don't know the div width, which is often the case, this solution works perfectly in all browsers: http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support
Artem Russakovskii
A: 

No, there is no way.

I'll use centering as an example of alignment. Text-align: center applied to an element centers all text inside an element. You cannot apply a property to an element that will center all its children. You can center children by changing properties of each child separately.

Look at the example in this article. The text inside the body is centering by styling the body, but centering the div is done by styling the div.

buti-oxa