I’m wondering if it’s possible, even though I’ve set my element to be fixed, with a top: 0
position, can I center it, or does it require a left position as well?
header {
position: fixed;
top: 0;
width: 100%;
background-color: yellow;
max-width: 200px;
margin: 0 auto;
}
<header>
<h1>Content</h1>
</header>
3
Answers
I think the problem is that you are setting position to fixed. Wrap your element in a container with fixed position and set the element position to relative, with
margin: auto
(1)Yes, you can center a fixed-position element horizontally using the
margin: 0 auto;
technique, even if it has atop: 0;
position. This will center the element within its containing block (usually the viewport) along the horizontal axis.In your example, the
<header>
element will be fixed to the top of the viewport (top: 0;
) and centered horizontally (margin: 0 auto;
). Here’s the corrected CSS:This will center the
<header>
element horizontally within the viewport while keeping it fixed at the top. Themax-width
property will limit its width to 200 pixels.margin: 0 auto
on a fixed element doesn’t work by itself. But by adding left and right as 0 it will. Also this snippet adds atext-align: center
so the text is aligned within the element.