Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed element that moves to top of page on scroll - CSS only

Tags:

html

css

noscript

I'm looking to produce the effect that is on this page: http://jonrohan.me/guide/css/creating-triangles-in-css/ - but with just CSS, no JavaScript (this would be trivial with JavaScript).

The effect I'm talking about is as follows:

  • Initially you see both the page header and the article title.
  • when you scroll the page header disappears.
  • The article title becomes fixed to the top of the page, so you always see it as you scroll.

The best I've managed to achieve so far is this:
http://jsfiddle.net/nottrobin/2FSvx/
But I don't like the duplication of the <nav> inherent in my solution.

Does anyone have any clever CSS/3 techniques they can think of to make it so that when you scroll down and the <header> disappears, the <nav> would naturally ride up to the top of the page?

like image 907
Robin Winslow Avatar asked Aug 23 '11 14:08

Robin Winslow


People also ask

How do I make div stick to Top of page on scroll?

To make an element sticky, use the following code: make sticky('#sticky-elem-id'); When an element becomes sticky, the code maintains the remaining content's position to prevent it from jumping into the gap left by the sticky element.

How do you make the element not move when scrolling?

And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.


1 Answers

Your example has some issues, if I scroll the webpage down or up sometimes the two navs overlap and the content is displayed twice and overlapping.

As far as I know, there is no such technique to obtain the same effect using only CSS, JS is required.

You can position elements using CSS only in a static way (normal page flow), fixed way (relative to browser window), or absolute/relative (relative to the nearest parent with a position set to relative).

You cannot "listen" to a scroll event like you would do with JavaScript, hence you cannot position an element relative to the amount of scrolling, nor change its position value in real time, because you will need JavaScript even for this.

CSS is a presentational markup language, properties you assign to elements using CSS rules cannot be changed on an event-basis.

You could do something like you did, but that means more markup language, more CSS and more maintenance difficulties.

You should use JS to optimize the user's experience, if a user has JS disabled, he/she will see the normal page behavior, otherwise the nav element will remain still, like all other websites do.

like image 190
Jose Faeti Avatar answered Oct 18 '22 01:10

Jose Faeti