html - 为什么我的 <img> 元素的堆栈顺序相反?

标签 html css image z-index

我正在创建一个可以更改背景的网站。我通过将我的背景图像设置为与我的浏览器相同的宽度/高度并设置它们的 opacity 来实现这一点。至 0 .

当我想要显示特定背景图像时,我使用 Javascript 设置背景图像的 opacity返回1 .所有的背景图像都用一个具有绝对定位的容器堆叠在一起。当我这样做时,我注意到了一些奇怪的事情。好像是后台<img>在代码中排在第一位的是在背景之上 <img>稍后在代码中。

根据我的理解,如果两个元素具有相同的 z-index并重叠,代码中后面的元素将在另一个元素之上。所以不应该 <img>代码中最后出现的元素位于最先出现的元素之上?相关代码如下。

HTML:

<body>
<div id="bg_container">
<img id="bg_3"  src="bg/bg_midori.png" width="1366px" height="662px">
<img id="bg1_2" src="bg/bg1_2.png" width="1366px" height="662px">

<!-- When I test my website, "bg_3" is on top of bg1_2. Should bg1_2 be on top of bg_3? Both <img> are supposed to have the "cover_bg" class but I removed so it's obvious that "bg_3" is on top of bg1_2 !-->

</div>

CSS:

 body{
    background-image:url('bg/bg_image.jpg');
    /*Above is the default background image */

    }

#bg_container{
    width:1366px;
    height:662px;
    position:absolute;
    top:0px;
    left:0px;
    z-index:-1;
    overflow:hidden;
    }

.cover_bg{
opacity:0;
}

知道为什么我的背景堆叠顺序 <img> s反了?

我注意到当我使用下面的代码时,背景 <img>后面的代码位于 <img> 之上正如我所料,继续进行。

<!DOCTYPE html> 
<html> 
<head> 
<style> 
img{
    position:absolute;
    left:0;
    top:0;
    }
</style>
</head> 
<body> 

<div id="bg_container">
<img id="bg_3" class="cover_bg" src="bg/bg_midori.png" width="1366px" height="662px">
<img id="bg1_2" class="cover_bg" src="bg/bg1_2.png" width="1366px" height="662px">

<!-- In this case bg1_2 is on top of bg_3, as expected !-->
</div>
</body>
</html>

最佳答案

只是一个可以帮助你的小链接。

来自这篇文章:what-no-one-told-you-about-z-index

Positioned elements with negative z-indexes are ordered first within a stacking context, which means they appear behind all other elements. Because of this, it becomes possible for an element to appear behind its own parent, which is normally not possible. This will only work if the element’s parent is in the same stacking context and is not the root element of that stacking context.

取决于您如何应用背景变化。一种方法是为 z-index 应用非负值,或者为 #bg_container 使用 background_url css 属性,可以通过 jQuery 修改。

关于html - 为什么我的 <img> 元素的堆栈顺序相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41204647/

相关文章:

objective-c - 指定图标的路径

javascript - 单击时连续旋转div

php - 上传文件表单 - 无法识别 $_FILES 变量

html - CSS :after is being pushed down by following elements

jquery - 使用 jQuery 将效果应用于当前页面/选项卡的 div 类

css - 如何将 DIV 放置在页面底部的两个垂直导航栏之间

html - HTML建议:我应该选择调整图库图像的大小还是使用单独的缩略图图像?

javascript - ES5中如何实现从服务器返回的图像延迟加载?

javascript - 突出显示时如何更改文本颜色?

javascript - 你如何设置一个 Javascript attachEvent 来监听来自服务器的数据?