How do I make :after box same size as parent and responsive? transform: scale(1) works, but why?

旧巷老猫 提交于 2021-02-17 06:21:28

问题


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;
}

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:

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);
}

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.


回答1:


It looks like it's because you didn't add a position property to your main element .card-image-none.

Because you are using absolute positioning for your :after element, it will position itself to the nearest element with a position set.

Just add position: relative to the .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:

Adding transform: scale(0) worked because transform creates a new positioning context (very last bullet on the page), just like adding position: relative



来源:https://stackoverflow.com/questions/61840695/how-do-i-make-after-box-same-size-as-parent-and-responsive-transform-scale1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!