html - 图片被 css 隐藏 :before pseudo-element unless opacity is different than 1

标签 html css pseudo-element

我尝试使用 css 伪元素设置图像的背景颜色:

<div class="my">
    <img src="http://cdn.impressivewebs.com/123rf-jan.jpg"/>
 </div>

CSS:

img {
    height: 100px;
    width: 100px;
}

.my:before {
    content: "";
    display: block;  
    position: absolute;  
    top: 0;  
    bottom: 0;  
    left: 0;  
    right: 0;  
    background: rgb(0,255,255);  
}

div {
    position: absolute;
    width: 200px;
    height: 200px;
    background-color: red;
}

我设法使其工作的唯一方法是设置 opacity:0.99; 或任何其他非 1 的值。我尝试使用 z-index 但没有成功。这种情况在 Chrome 和 Firefox 中都会发生。

opacity 设置为 1 或保留默认值会导致伪元素隐藏图像。 这是 fiddle :http://jsfiddle.net/zfYnu/

最佳答案

您还需要定位图像:

img {
    position: relative;
    height: 100px;
    width: 100px;
}

Updated fiddle

opacity 设置为小于 1 会导致图像创建自己的堆叠上下文。这会导致图像将自身堆叠在您已定位的 :before 伪元素之上。如果将 opacity 保留为默认值 1,则不会发生这种情况,从而导致 :before 伪元素堆叠在图像顶部。

请参阅CSS Color level 3 module有关不透明度section 9.9 of CSS2.1的信息有关堆叠上下文的详细信息。

关于html - 图片被 css 隐藏 :before pseudo-element unless opacity is different than 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17300183/

相关文章:

jquery - 使用带有 jquery 的 css 选择器在单个标记中选择两个 html 元素之一

html - CSS 悬停效果只适用于绝对定位?

html - 居中 "go to top"图片链接,但链接应用到图片高度的 100% 宽度

html - xslt 中的内部链接不起作用

html - Firefox 对 "display:table-cell; vertical-align:bottom;"的理解不同

CSS :before Pseudo-element not displaying background-image with IE8

CSS 计数器 : Can you increment by non-integers (i. e。 float )?

php - Paypal 表格未加密

html - 不使用 FQDN 时无法加载 IE 字体

css - 伪 :before not taking background property in chrome