HTML 个元素不重叠

HTML elements not overlapping

我试图在图像的右上角重叠一个关闭按钮,并将整个组件包裹在 div 中,以便我可以使用 JS 更轻松地复制它。我的 html 结构如下(...是无关信息):

<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>

我的样式表是

.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;
}

通过搜索其他 Whosebug 帖子,我发现两个定位元素和不同 z-index 的组合应该会产生我正在寻找的结果,但我却得到了这个(.thumb 元素被 JS 复制):

按钮没有覆盖在图像的右上角。

编辑:这是代码笔:

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

将此 css 用于右侧的关闭按钮

.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;
      right:15px;
    }
    .pic{
      width:100%;
    }

您在图像容器上设置了 position: relative

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

您希望按钮与图像重叠,但图像没有占据容器的整个宽度。

absolutely-positioned 按钮是相对于容器(上图中的阴影区域)放置的,而不是图像。

使图像与容器占据相同的space,然后您的按钮可以根据需要放置。

revised codepen

需要调整您的 .pic class 以便它用相对定位填充容器。然后再设置绝对定位的按钮就可以了

.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>