Reputation: 453
I tried centering my h1 in the body tag like this:
h1 {margin:0 auto}
But it doesn't center. How do I fix it?
Upvotes: 44
Views: 192427
Reputation: 3648
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>
Upvotes: 6
Reputation: 1173
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
Upvotes: 3
Reputation: 1
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.
Upvotes: 0
Reputation: 1
-div style="margin:0 auto; text-align:left; width:80px;"-
sample
change the width to change the position
Upvotes: 0
Reputation: 9
Alternatively, you could try this:
h1 {
text-align: center;
margin: 0px auto;
display; block;
}
Upvotes: 0
Reputation: 207901
In this case:
h1 {
text-align:center;
}
The margin:auto rule is used when you set a width on the element, which you haven't done.
Upvotes: 72