Search code examples
csscss-positionsticky

position: sticky breaks for tall content


I'm having some trouble getting position: sticky working for pages with (relatively) tall content. Below I've set up a simple page with content simulated with a div that is twice the viewport height. The sticky .palette tracks correctly with the page until the last couple dozen pixels when it falls off the top of the screen.

body, html {
	margin: 0;
	width: 100%;
	height: 100%;
	background: #334;
}

.palette {
	position: sticky;
	top: 0;
	width: 300px;
	height: 20px;
	background: orange;
	border-radius: 5px;
	margin: 10px;
}

.content {
	height: 200vh;
	margin: 10px;
	background: #556;
	border-radius: 20px;
}
<div class="palette"></div>
<div class="content"></div>

Neither using actual content, or setting the height of .content in pixels seems to change this effect. The distance from the bottom at which the palette starts scrolling with the page seems to change with the viewport height.

Why are my sticky divs not sticking correctly?


Solution

  • Position: sticky will only float over child elements and without a parent div it wont float over "content".

    You can find a good explanation of how it works from this medium article