Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Foundations The Box Model Positioning Properties

Fixed Position Element Relative to ViewPort or Body?

I was playing around with the code for this lesson in CodePen and I created a div with the class "fixed" in the HTML. In my CSS I applied the following styles to my class "fixed":

.fixed { position: fixed; width: 100%; height: 60px; background: #000; z-index: 40; }

I'm wondering why my fixed header does not go higher than the wrapper div. I thought that elements with a fixed position are relative to the viewport, so shouldn't it go right up to the top of the viewport? I did notice that the body has a margin-top of 70px. Is my fixed position div receiving inheritance from the body? Are fixed position elements relative to the body? Is the viewport and body the same? So confused.

Any help would be really appreciated! :)

Cheers, Zack

3 Answers

Kevin Korte
Kevin Korte
28,149 Points

Fixed position elements are positioned to the viewport...however you're not explicitly position the fixed element.

As I understand it, the body's margin and padding set the viewport size. Which would explain why your fixed element is inheriting the 70px.

Giving your .fixed element a position of top: 0; will ensure the fixed element lives at the top of the screen. The body's padding will make sure the rest of the content is pushed down below the fixed element since that element has been removed from the normal flow of the page.

I wish I could give a better explanation of how viewport, body, and html elements interact with each other. But, that's your fix.

Hi Zack,

The short answer is that fixed position elements are relative to the browser window, so that should be an easy way to think about it. Here are a couple resources to check out that should help!

CSS Position Property by W3Schools

Absolute, Relative, Fixed Positioning: How Do They Differ? by CSS Tricks

Also, be sure to check out the Treehouse course for an in-depth course on CSS Layout Techniques

Thanks Caleb!

That helps a bit. But it still doesn't make sense to me why my div with a fixed position is pushed down 70px from the top. The body element has a margin-top of 70px, but I thought that a fixed position element isn't relative to the body? It's relative to the viewport so it shouldn't be affected by the 70px of Margin.