Search code examples
htmlcsscentertext-align

How can I center a headline in CSS?


Newbie here with a simple (and no doubt dumb) question.

I’m trying to center a headline. I tried using the text-align property in CSS but to no avail:

h1 {
     text-align: center;
}

The headline is still flush left.

After doing a bit of digging, I tried this:

h1 {
     margin: 0 auto;
}

Still no luck. I then tried putting the headline into a DIV with the id "headline":

#headline {
     text-align: center;
}

And, when that still didn't work, I tried:

#headline {
     margin: 0 auto;
}

No luck.

I then came across a previous discussion about centering a DIV in CSS. One poster said that "a element fills 100% of parent element's width. If you want to center it, then the first thing you have to do is make it less than 100% wide. So set a width on the div, 200px or something."

When I tried

#headline {
     width: 1200px;
     margin: 0 auto;
}

nothing happened.

But when I tried:

#headline {
     width: 1200px;
     text-align: center;
}

the headline did shift to the center. The thing is, it isn't perfectly centered.

I've tried adjusting the width. That helps some but when I make the window bigger or smaller, the headline is no longer centered.

Any suggestions?

Apologies in advance for any inadvertent faux pas (this is my first time posting). Thanks for your help.


Solution

  • Just make the width 100% instead of a fixed pixel width. This is the default value (for a block element such as <h1>, but you must have changed something.) This will make it dynamic.

    See this example on JSFiddle.net.