Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

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

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:

overflowing box

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

correct placement

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...