Search code examples
htmlcssflexboxz-index

HTML elements not overlapping


I'm trying to overlap a close button in the top right corner of an image, and have this entire component be wrapped in a div so that I can use JS to replicate it easier. My html structure is as follows (... is for irrelevant info):

<div class="thumb-container">
    <div class="thumb">
        <div class="pic-container">
            <img class="pic" ... height="128">
            <button class="close-button">X</button>
        </div>
        <h1 class="title">Messenger: Facebook</h1>
    </div>
</div>

And my stylesheet is

.thumb-container {
  display: flex;
  flex-wrap: wrap;
}

.thumb {
  display: flex;
  flex-direction: column;
}

.pic-container {
  position: relative;
  z-index: 1;
}

.close-button {
  position: absolute;
  top: 0;
  z-index: 3;
}

From searching other stackoverflow posts, I found that the combination of two positioned elements and differing z-indexes should produce the result I'm looking for, but instead I got this (.thumb element is replicated with JS):

Result of code

The button is not overlayed in the top right corner of the image.

Edit: Here's the codepen:

https://codepen.io/jeanlucthumm/pen/GVRebe


Solution

  • Need to adjust your .pic class so it fills the container with relative positioning. Then you can set the absolutely positioned button and it will look fine.

    .thumb-container {
      display: flex;
      flex-wrap: wrap;
    }
    
    .thumb {
      display: flex;
      flex-direction: column;
    }
    
    .pic-container {
      position: relative;
      z-index: 1;
    }
    
    .pic {
      width: 100%;
      height: auto;
    }
    
    .close-button {
      position: absolute;  
      top: 5px;   
      right: 5px;
      z-index: 3;
    }
    <div class="thumb-container">
        <div class="thumb">
            <div class="pic-container">
                <img class="pic" src="https://via.placeholder.com/150">
                <button class="close-button">X</button>
            </div>
            <h1 class="title">Messenger: Facebook</h1>
        </div>
    </div>