Home > Software engineering >  How to make elements to stay under a sticky element css?
How to make elements to stay under a sticky element css?

Time:02-28

I have a contianer that contains some header and items. I want the header to be sticky and the items always be under him. The problem is the items always overlap the sticky element. I have demo code

.container {
  width: 100%;
  height: 500px;
  background: yellow
}

.sticky {
  position: sticky;
  top: 0;
  height: 50px;
}

.item {
  margin-top: 20px
}
<div >
  <div >
    sticky el
  </div>

  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
</div>

CodePudding user response:

The sticky element doesn't have a background, so the items underneath it are still visible. If it has a background it will cover them.

.container {
  width: 100%;
  height: 500px;
  background: yellow
}

.sticky {
  position: sticky;
  top: 0;
  height: 50px;
  background: #c00;
}

.item {
  margin-top: 20px
}
<div >
  <div >
    sticky el
  </div>

  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
  <div >
    fdsfdsf
  </div>
</div>

CodePudding user response:

.container {
  width: 100%;
  height: 800px;
  background: #ccc
}

.sticky {
  top: 0;
  height: 50px;
  background: #876;
  position: sticky;
}

.item {
  padding-top: 30px
}
<div >
  <div >
    sticky Header
  </div>

  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
  <div >
    information
  </div>
</div>

  • Related