如何制作一个伪元素来完全覆盖父级容器?

3
我已经创建了一个包含图片和文本的 div 元素。我想让伪元素 :before 完全覆盖父元素 div,但是我不知道该如何实现。 这是 jsfiddle 示例

.container {
    display:inline-block;
    width:33%;
    padding:15px;
    box-sizing:border-box;
    border:2px solid blue;
}
.container:before {
    content:"";
    background-color:green;
    width:100%;
    height:100%;
    display:block;
    transition:all 0.3s ease 0s;
    z-index:2;
}
.container img {
    max-width:100%;
}
.container h2 {
    font-size:1.5em;
    font-style:normal;
    text-decoration:none;
    font-weight:400;
}
<div class="container">
    <h2>Lorem ipsum</h2>
    <img alt="" src="http://lorempixel.com/400/300">
</div>


1
我不是很清楚,你的演示代码中有什么问题,你想要实现什么却没有成功呢? - Hayden Schiff
3个回答

4

请执行以下操作。

  • Add position: relative; to .container
  • Then add these lines to .container:before:

    position: absolute;
    top: 0;
    left: 0;
    

欢迎来到Stack Overflow。这是一个很好的首篇文章,但我仍然想建议您阅读[答案]。该页面将解释最佳实践,这将增加您答案被接受的机会。 - Dan Beaulieu

1

Here’s my answer:

https://jsfiddle.net/2y6uh3j6/4/

主要见解:

  1. 您需要在父容器中建立一个定位上下文。这可以通过在.container上设置position: relative来实现。

  2. 可以通过使用position: absolute; top: 0; left: 0; right: 0; bottom: 0;(允许您放弃heightwidth)来避免填充问题。


0
你只需要给父元素和:before伪元素添加定位。虽然我不确定你对红色叠加层的意图是什么。

http://jsfiddle.net/basyqLv8/

.container {
    position:relative;

.container:before {
    position: absolute;
    top: 0;
    left: 0;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接