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 Layout Basics Positioning Page Content Fixed Positioning

René Sánchez
René Sánchez
9,954 Points

How can I position the header so that it appears fixed to the top only if i hover over the top of the viewport?

I think i have an idea but some help would be awesome!

2 Answers

Steven Parker
Steven Parker
229,786 Points

I'm not entirely sure I understand what you want to do, but it sounds like this might be close:

header:hover {
  position: fixed;
  top: 0;
}

The catch is that since the item you are hovering is going to move, this effect may be rather unstable.

To do a better job you might need to hover over some other object already at the top and then move your header. For that, I think you'd need JavaScript. I can't think of any way to do that in pure CSS, unless you can make the header a descendant of the object you will hover over.

René Sánchez
René Sánchez
9,954 Points

Thanks Steven bro, but that's not exactly what i needed, but really appreciate it! Either way, i also think that it takes more than css but i got the feeling that i might be wrong. Im gonna check Adam's response (below), it seems logical to me :P

Adam Hill
Adam Hill
7,492 Points

Just to expand on what Stephen said about the element being a child of what you're hovering over, if you didn't want to use JavaScript, although it's a little messy repeating elements, you could create a new/second header/navigation object as the last item before the body, and reveal it on hover.

.secondaryNav {
    display:block;
    position:fixed;
    top:0;
    opacity:0;
}

body:hover .secondaryNav{
    opacity:1;
}

Be aware it will always be there even if you can't see it, so you might want to consider experimenting setting z-index on it and other elements on the page so it starts off below the content and moves to the front on hover, or setting it's height to 0 and overflow to hidden and setting the height on hover.

This method would allow some css transition effects (animating either/both opacity and height of the element so it appeared to fade/slide in).

René Sánchez
René Sánchez
9,954 Points

Thanks a lot Adam, i'm gonna try it out, really seems logic to me and it looks like a nice practice. I am afraid i'm gonna need more than just Css but i might be making newbie assumptions.