I tried centering my h1 in the body tag like this:
h1 {margin:0 auto}
http://jsfiddle.net/qPDwY/
But it doesn't center. How do I fix it?
Just use padding top and bottom, it will automatically center the content vertically.
You can add line-height:51px to #AlertDiv h1 if you know it's only ever going to be one line. Also add text-align:center to #AlertDiv . The demo below also uses negative margins to keep the #AlertDiv centered on both axis, even when the window is resized. Yes, it will be only one line.
Use a container element and set a specific max-width . A common width many websites use is 960px. To actually center the page, add margin: auto .
To set the heading alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <h1> to <h6> tag, with the CSS property text-align. HTML5 do not support the align attribute of the heading tag, so the CSS style is used to set alignment.
In this case:
h1 { text-align:center; }
jsFiddle example
The margin:auto rule is used when you set a width on the element, which you haven't done.
You can center it by setting the width.
<body> <h1>My Title</h1> </body>
CSS
h1 { width:500px; margin: 0 auto; background: gray; text-align: center; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With