Search code examples
htmlcssstackpositionabsolute

CSS - position: absolute is stacking images


My HTML is

    <section class="container">
        <div class="tiktok">
            <img src="img/langhe.jpeg" class="blurredImg">
            <img src="img/pp.jpeg" class="center">
        </div>

        <div class="tiktok">
            <img src="img/langhe.jpeg" class="blurredImg">
            <img src="img/pp.jpeg" class="center">
        </div>

        <div class="tiktok">
            <img src="img/langhe.jpeg" class="blurredImg">
            <img src="img/pp.jpeg" class="center">
        </div>
    </section>

My CSS is:

.container {
height:100%;
width: 100%;
overflow-y: scroll;
scroll-snap-type: mandatory;
scroll-snap-points-y: repeat(3rem);
scroll-snap-type: y mandatory;
position: relative;
z-index: 1;
border: none;
}

.blurredImg{
width: 100%;
height: 100%;
filter: blur(8px);
-webkit-filter: blur(8px);
}

.tiktok {
height: 100%;
width:100%;
background-color: black;
scroll-snap-align: start;
}

.center{
margin: auto;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
border-radius: 50%;
border: 10px solid white;
}

while "langhe.jpeg" is displayed in 3 different divs one after another, "pp.jpeg" images are displayed one on top of each other, instead of being displayed each on a single div.

I'm pretty sure the issue is on "position: absolute;" in the "center" class, but I might be wrong.


Solution

  • If each element with .center has position: absolute then you need to set position: relative on the parent (.tiktok)

    .container {
      height: 100%;
      width: 100%;
      overflow-y: scroll;
      scroll-snap-type: mandatory;
      scroll-snap-points-y: repeat(3rem);
      scroll-snap-type: y mandatory;
      position: relative;
      z-index: 1;
      border: none;
    }
    
    .blurredImg {
      width: 100%;
      height: 100%;
      filter: blur(8px);
      -webkit-filter: blur(8px);
    }
    
    .tiktok {
      height: 100%;
      width: 100%;
      background-color: black;
      scroll-snap-align: start;
    
      /* Added by me */
      position: relative;
    }
    
    .center {
      margin: auto;
      position: absolute;
      top: 50%;
      left: 50%;
      -ms-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
      border-radius: 50%;
      border: 10px solid white;
    }
    <section class="container">
      <div class="tiktok">
        <img src="https://picsum.photos/200" class="blurredImg">
        <img src="https://picsum.photos/200" class="center">
      </div>
    
      <div class="tiktok">
        <img src="https://picsum.photos/200" class="blurredImg">
        <img src="https://picsum.photos/200" class="center">
      </div>
    
      <div class="tiktok">
        <img src="https://picsum.photos/200" class="blurredImg">
        <img src="https://picsum.photos/200" class="center">
      </div>
    </section>