我该如何使:after框的大小与父级相同并具有响应能力?变换:scale(1)有效,但是为什么呢? [英] How do I make :after box same size as parent and responsive? transform: scale(1) works, but why?
问题描述
我正在为具有简单渐变背景的框设计样式,并在其上覆盖SVG背景图像,如下所示:
I'm styling a box with a simple gradient background and overlaying it with an SVG background image, like this:
HTML:
<div class="card-image-none">
<img src="/graphics/16-9.png" class="w-100 img-fluid">
</div>
CSS:
.card-image-none {
height: auto;
background-image: linear-gradient(to bottom, rgba(0,0,0,0.05) 0%,rgba(0,0,0,0.2) 100%);
}
.card-image-none:after {
content: "";
display: block;
position: absolute;
top: 0;
left: 0;
background-image: url('/fontawesome/svgs/solid/quote-right.svg');
background-size: 40%;
background-position: 50% 50%;
background-repeat: no-repeat;
width: 100%;
height: 100%;
opacity: 0.1;
}
顺便说一句,图像16-9.png 是一个透明的盒子,用于维护盒子的特定(响应)尺寸.问题在于,由于 height:100%
,在 card-image-none:after
中定义的重叠图像不会停留在父框中.有时看起来可能像这样:
BTW, image 16-9.png is a transparent box that's used to maintain a specific (and responsive) dimension to the box. The problem is that the overlay image defined in card-image-none:after
doesn't stay confined within the parent box because of height: 100%
. It can sometimes look like this:
但是,如果我在 card-image-none 中添加 transform:scale(1);
,则它会限制在父框中,如下所示:
But if I add transform: scale(1);
to card-image-none, then it stays confined within the parent box, like this:
.card-image-none {
height: auto;
background-image: linear-gradient(to bottom, rgba(0,0,0,0.05) 0%,rgba(0,0,0,0.2) 100%);
transform: scale(1);
}
当我包含 transform:scale(1)
时,它可以按我的意愿工作,我不确定为什么或是否有更好的方法来执行此操作而不进行转换.
It works as I want when I include transform: scale(1)
, and I'm not sure why or if there's a better way to do this without transform.
推荐答案
它看起来像是因为您没有在主元素 .card-image-none中添加
. position
属性
It looks like it's because you didn't add a position
property to your main element .card-image-none
.
由于您对:after
元素使用了 absolute
定位,因此它将自身定位到具有位置集的最近的元素.
Because you are using absolute
positioning for your :after
element, it will position itself to the nearest element with a position set.
只需将 position:relative
添加到 .card-image-none
.card-image-none {
position: relative;
height: auto;
background-image: linear-gradient(to bottom, rgba(0,0,0,0.05) 0%,rgba(0,0,0,0.2) 100%);
}
特定查询的背景知识更多
A little more background to the specific query:
添加 transform:scale(0)
之所以有效,是因为transform 创建一个新的定位上下文(页面上的最后一个项目符号),就像添加 position:relative
Adding transform: scale(0)
worked because transform creates a new positioning context (very last bullet on the page), just like adding position: relative
这篇关于我该如何使:after框的大小与父级相同并具有响应能力?变换:scale(1)有效,但是为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!