43

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
user3182981
  • 443
  • 1
  • 4
  • 4
  • 1
    Use `text-align:center`... http://jsfiddle.net/9bSnT/ .. The `h1` is a block level element with a width of 100%.. `margin:0 auto` won't work in this instance. – Josh Crozier Jan 10 '14 at 18:22
  • `text-align: center`? `h1` is by default 100% width. – putvande Jan 10 '14 at 18:22
  • Margin: 0 auto; Works in a fixed or 100% width. You can also use text-align: center; but that will only work again as long as your width on your site is set to 100% or fixed and centered itself. The other thing you should be careful of is using text-align: center; will center all Unless you specifically point to a particular nested h1 as here .yourclass h1 {text-align: center} – Cam Jan 10 '14 at 18:30

6 Answers6

68

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
6

You can center it by setting the width.

h1 {
    width:500px;
    margin: 0 auto;
    background: gray;
    text-align: center;
}
<body>
     <h1>My Title</h1>
</body>
Bilal
  • 3,191
  • 4
  • 21
  • 49
Ceres
  • 3,524
  • 3
  • 18
  • 25
3

text-align: center is best choice but if you still want to center it using margin: 0 auto you have assign some width to H1 (a block) element.

You can center a block-level element by giving it margin-left and margin-right of auto (and it has a set width, otherwise it would be full width and wouldn’t need centering). That’s often done with shorthand like this:

.center-me {
  margin: 0 auto;
}

Source: https://css-tricks.com/centering-css-complete-guide/#horizontal-block

Suryansh Singh
  • 1,123
  • 7
  • 15
0

Alternatively, you could try this:

h1 {
    text-align: center;
    margin: 0px auto;
    display; block;
}
timmyblog
  • 9
  • 2
  • 1
    By default the h1 is a block level element and without a width the margin:0 auto does nothing. – j08691 Jan 10 '14 at 18:31
0

-div style="margin:0 auto; text-align:left; width:80px;"- sample

change the width to change the position

0

What j09691 said does work, but not all the time.

This is why I use:

/* Put this inside element/class. */
transform: translateX(400px);

If it doesn't fit in the center of the screen for you, just adjust it. Of course, you could use some css and/or js magic to automatically adjust it.