user1401379
user1401379

Reputation:

Vertically and Center Align Text

I have a h1 within the body and want to vertically align and center align this text.

I know I can use the position: absolute; and then margin-top: "HALF OF HEIGHT"; but this h1 changes on refresh and has different widths. The height is always the same so I can vertically align it fine but it's center aligning it. I can't use text-align: center; becuase the h1 is positioned absolute so it won't work.

Is there an easier way to do this?

Thanks!

Upvotes: 0

Views: 169

Answers (2)

wanovak
wanovak

Reputation: 6127

Depending on the rest of your layout, this may work:

h1 {
    display: block;
    text-align: center;
    line-height: /* height of container */
}

http://jsfiddle.net/xC3vn/

Upvotes: 0

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

Given that the element doesn't have a background, you could do this to horizontally center an element with absolute positioning:

.your-element {
    position: absolute;
    width: 100%;
    text-align: center;
}​

A working fiddle: http://jsfiddle.net/VSySg/

Upvotes: 1

Related Questions