Search code examples
htmlcsscss-position

Sticky positioned child ignores parent's padding


How can I prevent the sticky element from going behind the header?

The current snippet uses padding top on the parent, I tried also using margin-top on an extra child instead or transparent 50px border but it doesn't seem to work.

I know I can easily use top: 50px; on the sticky in this case but I want to integrate this part in a React Component and using specific sizes make it harder to combine different Components since they all have to share the top size.

How can I make the header/padding be "solid" and make the sticky unable to go through?

body{
  background: rgb(200,200,200);
  padding:0px;
  margin:0px;
}
header{
  height: 50px;
  font-size: 2em;
  background: aqua;
  opacity: 0.6;
  text-align:center; 
  position: fixed; 
  width: 100%;
}
.content-wrapper{
  padding-top: 50px; /* keeps the header space */
  
  height: 800px; /*for demo*/
}
.sticky{
  position: sticky;
  top:0;
}
<header>header</header>
<div class="content-wrapper">
  <div class="sticky">
  Hello, I am a sticky element
  <div>
<div>


Solution

  • Not sure if this has drawbacks I'm unaware of or if it is viable in your case, but translateY seems to work. It's definitely hacky though.

    body{
      background: rgb(200,200,200);
      padding:0px;
      margin:0px;
    }
    header{
      height: 50px;
      font-size: 2em;
      background: aqua;
      opacity: 0.6;
      text-align:center; 
      position: fixed; 
      width: 100%;
    }
    .content-wrapper{
      position: relative;
      height: 800px; /*for demo*/
      transform: translateY(50px);
    }
    .sticky{
      position: sticky;
      top:0;
    }
    
    .spacer {
      height: 200px;
    }
    <header>header</header>
    <div class="content-wrapper">
    <div class="spacer"></div>
      <div class="sticky">
      Hello, I am a sticky element
      <div>
    <div>