Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center an h1 in the body

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?

like image 819
user3182981 Avatar asked Jan 10 '14 18:01

user3182981


People also ask

How do I center my h1 vertically?

Just use padding top and bottom, it will automatically center the content vertically.

How do I center a h1 tag in a div?

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.

How do I center a body in HTML?

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 .

How do you center align headers?

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.


2 Answers

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.

like image 173
j08691 Avatar answered Sep 29 '22 22:09

j08691


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; } 
like image 20
Ceres Avatar answered Sep 29 '22 23:09

Ceres