Home > front end >  position two divs with position fixed after each other without setting explicit heights
position two divs with position fixed after each other without setting explicit heights

Time:06-30

With the snippet below I would like to have the fixed divs appear in the screenshot below preferably without having to set an explicit height or margin-top because if I do that, I will need different heights at different breakpoints and I don't want to use javascript.

enter image description here

Is it possible to stack position: fixed divs in this way without explicit heights or margin-top?

body {
  text-rendering: optimizespeed;
  height: 100%;
  background-color: rgb(241, 241, 241);
}

#root {
  height: 100%;
  display: grid;
  grid-template:
    "header" auto
    "main" 1fr
    "footer" auto / 1fr;
}

.scroller {
  height: 150vh;
  overflow: auto;
  border: 10px solid red;
}

main {
  position: relative;
}

.ours {
  border: 10px solid blue;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0px;
  top: 0px;
}

.third-party {
  align-items: center;
  background-color: rgb(255, 255, 255);
  box-sizing: border-box;
  display: grid;
  grid-template-areas: "leading center trailing";
  justify-content: space-between;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0px;
  top: 0px;
  z-index: 1000;
  border: 3px solid green;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link type="text/css" rel="stylesheet" href="/src/styles.css" />
  </head>

  <body>
    <div id="root">
      <header >Should be no.1</header>
      <main>
        <div >
          <header>should be no.2</header>
        </div>
        <div >
          scroller should come after 2
        </div>
      </main>
    </div>
  </body>
</html>

CodePudding user response:

wrap div one and two with another div and apply position:sticky to it with top:0

Sample:

.one {
  background-color: red;
}

.two {
  background-color: green;
}

.scroll {
  height: 800px;
  border: 2px dashed;
  padding: 10px;
}

.fixed {
  position: sticky;
  top: 0;
  width: 100%;
}

.main {
  padding: 0;
  margin: 0
}
<div >
  <div >
    <div >Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </div>
    <div >Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
  </div>
  <div > Something in scroll div </div>
</div>

  • Related