Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed header in CSS for conditional scroll down?

Tags:

css

I want to make a header div (like a banner) fixed only when the header is trying to go out of the screen as the user scrolls down. Is it possible to do without using JS? For an example in Facebook timeline, if we scroll down a banner floats up as soon as the page's header goes out of the screen. My question is, is it possible to do with only CSS?

In case it is not clear enough, I want to know whether a style "position: fixed" can be applied conditionally like when 80px of the page is scrolled.

like image 699
Roy Avatar asked Jan 27 '13 18:01

Roy


2 Answers

Yes. You can do it with just CSS. This is done by having a normal scrolling header, placed above a fixed one, which shows up only after the normal one scrolls up above it. This is kind of how http://techcrunch.com is doing it.

Update [10/31/2013] - Techcrunch changed their UI recently so you cannot see this there anymore!

Check this demo: http://jsfiddle.net/WDnyb/2/

HTML

<div class="header">Header</div>
<div class="outer">
    <span class="banner">LOGO</span>
    <div class="header">Header</div>
</div>
<div class="content">Content</div>

Relevant CSS

.header {
    width: 100%;
    position: fixed;
    top: 0;
    bottom: auto;
}
.outer {
    position: relative;
    height: 100px;
}
.outer .header {
    position: absolute;
    bottom: 0;
    z-index: 2;
    top: auto;
}
.content {
    height: 1500px;
    margin-top: 100px;
}
like image 112
techfoobar Avatar answered Sep 22 '22 20:09

techfoobar


This can now be done properly and without javascript with position: sticky.

Refer to https://css-tricks.com/position-sticky-2/ for examples.

warning: At the moment of writing, it is not supported on IE11, opera mini, and android's stock browser: https://caniuse.com/#feat=css-sticky

like image 37
L0laapk3 Avatar answered Sep 21 '22 20:09

L0laapk3