Reverend2100
Reverend2100

Reputation: 880

Overlay 2 DIVs where one is Static and the other is Scrollable

I am creating a page where the Hero image must stay centered on screen as the visitor scrolls down the page. Elements that are scrollable will 'frame' the Hero image as they scroll past.

However, my initial screen (above-the-fold) must have the Hero image, and the first Frame image, overlaid, and no matter how I mix position: sticky with fixed, absolute, static... Nothing will work, and the Frame appears below the Hero (i.e. the div will not overlap/overlay).

Also, I want the Frame layer in front of the Hero, but z-index appears to make no difference.

here is my layout:

<div class="homepage">
    <div class="hero-image">
        <img src="images/hero-can.png">
    </div>
    <div class="homeScreen1">
        <img src="images/water-splash.png">
    </div>
 </div>

here is my CSS:

.homepage {
    background-image: url('images/background.jpg');
}

.hero-image {
    margin: 0 auto;
    max-width: 512px;
    position: sticky;
    top: 0;
    z-index: 99999;
}

.homeScreen1 {
    margin: 0 auto;
    width: 1024px;
    text-align: center;
    z-index: 999999;
}

Appreciate any help!!

Upvotes: 1

Views: 1455

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

You can achieve that with these steps:

  1. Set the position of the container (i.e. homepage) to relative.
  2. Set the position of the hero to fixed, so it doesn't scroll with the container.
  3. Set the position of the frames to absolute with z-index higher than the hero so it can overlay it.

You can see the example below. I set the container background color so we can see it and set its height to 1000px so we can test it scrolling, so those settings are for demo purpose only.

To center your hero and frames, you need these steps:

  1. Set the left and right margins to auto.
  2. Set a fixed width. This is required for the auto margins to work.
  3. Set the left and right to zero. This is required for fixed and absolute layouts to be centered.

.homepage {
    background-color: #0ff;
    height: 1000px;
    position: relative;
}

.hero-image {
    position: fixed;
    width: 150px;
    margin: 0 auto;
    left: 0;
    right: 0;
}

.homeScreen1 {
    position: absolute;
    width: 160px;
    margin: 0 auto;
    top: 200px;
    left: 0;
    right: 0;
    z-index: 1;
}
<div class="homepage">
    <div class="hero-image">
        <img src="http://placehold.it/150x150">
    </div>
    <div class="homeScreen1">
        <img src="http://placehold.it/160x160">
    </div>
 </div>

Upvotes: 1

Related Questions