z索引可以用于图片前面的按钮吗?

Can z-index be used for buttons in front of pictures?

本文关键字:前面 按钮 索引 用于      更新时间:2023-09-26

使用 CSS,我试图使 z-index 成为在我的主图片(也是我的用户图片)前面放置几个按钮的解决方案,但它不起作用!我已经尝试修复它一段时间了,这是代码 ->此代码用于考虑 chrome 浏览器与 100%,整页

//As you may see below, I have attempten wrapping the picture in a div, and in css I have tried adding position relative. It doesn't work though!
button {
  z-index: 5;
  position: relative;
  font-size: 60px;
  color: black;
  background-color: orange;
  border-radius: 20px;
}
#background-image-Menu {
  width: 100%;
  height: auto;
  z-index: 0;
  position: relative;
}
#background-image-Menu #bim {
  width: 100%;
  height: auto;
  z-index: 0;
  position: relative;
}
<div id="background-image-Menu">
  <img src="https://lh6.ggpht.com/-LEZqqfbyUAC2c8P35J8f4vIRxFBXD8CG9lFBztPYwzdYoa6EPEyh7X0uNn39MwEjh02Og=s142" id="bim" />
</div>
<button id="start_engine">Create new game</button>
<br>
<br>
<button id="load_game">Load game</button>
<br>
<br>

z-index只控制堆叠顺序。您的元素仍然以通常的线性方式布局。

如果希望它们占据相同的 x 和 y 坐标,则需要将其中一个元素移动到另一个元素的位置。您可以使用负边距、设置top或其他一些技术来做到这一点。

也就是说,看起来您的实际目标是拥有背景图像。您的图像似乎没有传达任何信息(并且没有alt属性),因此它可能不是内容图像。

#menu {
  background: url('https://lh6.ggpht.com/-LEZqqfbyUAC2c8P35J8f4vIRxFBXD8CG9lFBztPYwzdYoa6EPEyh7X0uNn39MwEjh02Og=s142') no-repeat;
  background-size: 100% 100%;
  width: 100%;
  overflow: hidden;
  }
button {
  display: block;
  font-size: 60px;
  color: black;
  background-color: orange;
  border-radius: 20px;
  margin: 20px;
}
<div id="menu">
<button id="start_engine">Create new game</button>
<button id="load_game">Load game</button>
</div>

因为它们都定位为相对的,所以它们不会放在图像的顶部。按钮需要设置为position: absolute;或图像应该。实际上,您希望图像绝对定位以实现您要做的事情。

当您为图像提供绝对位置时,它的外观如下:http://jsfiddle.net/w1gjufys/


或者,您也可以使用top: -100px;来定位按钮,其中"-100px"值可以更改为您想要的值。分别,您将使用left: 100px;水平移动它。这是使用此方法的样子:http://jsfiddle.net/w1gjufys/2/


Z 索引控制事物的 z 轴(并赞扬您使用 z-index 在元素上应用静态以外的位置)。Z 轴等效于从鸟瞰图查看一堆卡片,其中第一张卡片(也是您会看到的唯一卡片)在 z 索引中具有最高值。


请记住,您不应该使用<br>标签作为间隔的方法,因为这会使您的 html 看起来很混乱。改为应用边距。为您的按钮指定一个类或 ID,并专门针对它们来控制每个按钮应获得多少边距。