css Z索引不适用于图像和按钮[重复]

kuhbmx9i  于 2023-03-14  发布在  其他
关注(0)|答案(1)|浏览(115)

此问题在此处已有答案

Why can't an element with a z-index value cover its child?(5个答案)
Why does z-index not work?(10个答案)
4天前关闭。
我正在为一个学校项目制作一个关于美洲狮的信息站点。我试图在图像后面放置一组可以转到其他页面的按钮,这样当你单击它时,按钮就会显示出来。问题是z轴不允许按钮位于图像后面。

#image {
  width: 40%;
  border-radius: 20px;
  display: block;
  margin: auto;
  opacity: 1;
  transition-duration: 0.4s;
  cursor: pointer;
  border: 4px solid black;
  z-index: 10;
  /* set higher z-index value */
}

#image:hover {
  border: 4px solid white;
  width: 42.5%;
}

#image.clicked {
  opacity: 0;
  transition-duration: 1s;
  pointer-events: none;
}

.hidden {
  display: none;
}

h3 {
  text-align: center;
  margin-bottom: 60px;
}

.image-container {
  position: relative;
}

.buttons {
  position: absolute;
  margin: auto;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  justify-content: center;
  gap: 10px;
  z-index: 5;
  /* set lower z-index value */
  top: 50%;
}

button {
  padding: 10px 20px;
  border-radius: 20px;
  border: none;
  background-color: white;
  color: black;
  font-size: 16px;
  cursor: pointer;
}

button:hover {
  background-color: black;
  color: white;
}
<div class="image-container">
  <div class="buttons">
    <button>Button 1</button>
    <button>Button 2</button>
    <button>Button 3</button>
    <button>Button 4</button>
  </div>
  <img src="https://cdn.britannica.com/20/93520-050-3E663489/Puma.jpg" id="image" onclick="this.classList.add('clicked');">
</div>

我试着改变z轴来把图像和按钮分开,但是不起作用,所以我不知道该怎么办。

db2dz4w8

db2dz4w81#

使用z-index时,必须始终确保要操作的元素具有position而不是static
在本例中,我将position: relative应用到图像中,这样就可以完成任务。
祝你好运!

#image {
  width: 40%;
  border-radius: 20px;
  display: block;
  margin: auto;
  opacity: 1;
  transition-duration: 0.4s;
  cursor: pointer;
  border: 4px solid black;
  z-index: 10; /* set higher z-index value */
  position: relative;
}

#image:hover {
  border: 4px solid white;
  width: 42.5%;
}

#image.clicked {
  opacity: 0;
  transition-duration: 1s;
  pointer-events: none;
}

.hidden {
  display: none;
}

h3 {
  text-align: center;
  margin-bottom: 60px;
}

.image-container {
  position: relative;
}

.buttons {
  position: absolute;
  margin: auto;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  justify-content: center;
  gap: 10px;
  z-index: 5; /* set lower z-index value */
  top: 50%;
}

button {
  padding: 10px 20px;
  border-radius: 20px;
  border: none;
  background-color: white;
  color: black;
  font-size: 16px;
  cursor: pointer;
}

button:hover {
  background-color: black;
  color: white;
}
<div class="image-container">
  <div class="buttons">
    <button>Button 1</button>
    <button>Button 2</button>
    <button>Button 3</button>
    <button>Button 4</button>
  </div>
  <img src="https://cdn.britannica.com/20/93520-050-3E663489/Puma.jpg" id="image" onclick="this.classList.add('clicked');">
</div>

相关问题