Doug Smith
Doug Smith

Reputation: 29326

How do I center text relative to its parent div with CSS?

I know I can use text-align: center; on the parent div to center all its child elements, but what if I don't want all the child elements centered? I just want, say, one child element centered relative to the parent.

Say I have everything within a wrapper div. Some headers, forms, etc. But at the bottom I want to center a small line of text crediting something. How would I achieve that if its hierarchy is body > div.wrapper > div.credit?

Upvotes: 0

Views: 173

Answers (2)

Aliencaterpillar
Aliencaterpillar

Reputation: 41

Only specify which div to centre by saying which one:

div {
text-align:/* whatever align for the rest */
}

div:credit {
text-align:center;
}

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157384

So why you are complicating the CSS here? Simply wrap that text in a div and use text-align: center; for that particular div and you are done

And if you want to declare in a CSS hierarchy manner just use this

body div:last-child {
   text-align: center;
}

Note: Be sure the text you want to be centered is the last div you are using else don't use last-child selector, better declare a class

Upvotes: 2

Related Questions