Rob
Rob

Reputation: 1495

Dynamically position div below a fixed position div

I'm trying to position the second pink div to be dynamically vertically positioned based on the height of the top first div (hero) to then scrolls above it.

Currently it has the following code:

body {
  margin: 0px;
  font-family: helvetica;
}

h1 {
  font-size: 4rem;
  text-transform: uppercase;
  color: yellow;
}

.hero {
  position: fixed;
  z-index: 0;
  background: grey;
  padding: 40px;
  top: 0;
}
.block {
  background: pink;
  height: 90vh;
  position: relative;
  z-index: 0;
  padding: 40px;
  margin-top: 90vh;
}
h2 {
  font-size: 3rem;
}
<div class="hero">
  <h1>Intro block to be fixed position and under all other content. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non orci eu odio suscipit sagittis. Sed vitae pretium sapien, vitae facilisis tellus. Praesent gravida interdum quam, id accumsan ex congue quis.
</h1>
</div>

<div class="block">
    <h2>Second block to be position below the hero block and overlay on scroll. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non orci eu odio suscipit sagittis. Sed vitae pretium sapien, vitae facilisis tellus. Praesent gravida interdum quam, id accumsan ex congue quis.
</h2>
</div>

Is there a smart way to do this with CSS

Upvotes: 1

Views: 74

Answers (2)

Rob
Rob

Reputation: 1495

Seems to be an ongoing issue with this not working as expected with iOS, Chrome and Safari

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272590

sticky can help here:

body {
  margin: 0px;
  font-family: helvetica;
}

h1 {
  font-size: 1rem;
  text-transform: uppercase;
  color: yellow;
}

.hero {
  position: sticky;
  background: grey;
  padding: 40px;
  top: 0;
}
.block {
  background: pink;
  min-height: 100vh;
  position: relative;
  z-index: 1;
  padding: 40px;
}
h2 {
  font-size: 3rem;
}
<div class="hero">
  <h1>Intro block to be fixed position and under all other content. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non orci eu odio suscipit sagittis. Sed vitae pretium sapien, vitae facilisis tellus. Praesent gravida interdum quam, id accumsan ex congue quis.
</h1>
</div>

<div class="block">
    <h2>Second block to be position below the hero block and overlay on scroll. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non orci eu odio suscipit sagittis. Sed vitae pretium sapien, vitae facilisis tellus. Praesent gravida interdum quam, id accumsan ex congue quis.
</h2>
</div>

Upvotes: 2

Related Questions