Maxwell s.c
Maxwell s.c

Reputation: 1668

CSS position sticky doesn't work properly when element is inside another

i'm trying to make an element stick to the top, but it doesn't work when it's inside another div. The header div doesn't have any style by itself.

nav {
    height: 50px;
    background: lightgreen;
    position: sticky;
    top: 0;
}

main {
    height: 200vh;
    background: linear-gradient(180deg, black 0%, white 100%);
}

aside {
    height: 30px;
    background: red;
}
<header>
  <aside></aside>
  <nav></nav>
</header>
<main></main>

If i apply sticky on the header element it works, but it will also drag the aside element, i want only the nav element to be sticky:

header {
    position: sticky;
    top: 0;
}

nav {
    height: 50px;
    background: lightgreen;
}

main {
    height: 200vh;
    background: linear-gradient(180deg, black 0%, white 100%);
}

aside {
    height: 25px;
    background: red;
}
<header>
    <aside></aside>
    <nav></nav>
</header>
<main></main>

This limits a lot what i can do with sticky property if it's intended. The only solution i've found is to remove the header element and keep all elements inside body.

Upvotes: 1

Views: 7702

Answers (3)

Temani Afif
Temani Afif

Reputation: 272723

if your aside will always have a fixed height use negative top value and make the parent container sticky:

nav {
  height: 50px;
  background: lightgreen;
}

header {
  position: sticky;
  top: -30px;
}

main {
  height: 200vh;
  background: linear-gradient(180deg, black 0%, white 100%);
}

aside {
  height: 30px;
  background: red;
}
<header>
  <aside></aside>
  <nav></nav>
</header>
<main></main>

Upvotes: 2

Kate
Kate

Reputation: 186

An element with position:sticky; only becomes fixed with respect to its immediate container I'm afraid, so your best solution without resorting to Javascript would be to move nav inside main.

Upvotes: 2

maysam besharaty
maysam besharaty

Reputation: 29

Stiky position acts just inside parent element. So if your element is directly under body, it'll act as you need. You can use javascript for whole page stiky.

window.onload=window.onscroll=window.onresize=function(){
var s=window.scrollY;
var mp=Math.max(0,250-s);
document.getElementById("stiky").style.top = mp+"px";
}
#parent{height:3000px;}
#child{height:300px; background:#999}
#stiky{position:fixed; width:100%; height:50px;background:#ff0}
<div id="parent">
<div id="child">
<div id="stiky"></div>
</div>
</div>

Upvotes: 1

Related Questions