Search code examples
htmlcsscentering

h2 element won't stay centered unless it is set to 100%


This seems like it should be a very simple issue to me, although I just can't figure it out on my own. I have a h2 element that I want to keep at 85%, and it contains a short line of text. I want it to be centered in its containing div, not just for the text to be centered in the h2 element. Here's some code:

<div class="main">
  <div class="secondary">
      <h2>Three words of text</h2>
  </div>
</div>

CSS:

div.main{
  text-align:center
}
div.secondary{
  text-align:center
}
h2{
  text-align:center
  width:85%
}

I made a Fiddle, too

Thanks to anyone who can help.


Solution

  • Add:

    margin: 0 auto;
    

    To the h2 style rule.

    http://jsfiddle.net/wF57b/1/