【问题标题】:How do I make pseudo-element scale with the image?如何使用图像制作伪元素比例?
【发布时间】:2021-08-28 04:35:45
【问题描述】:

我在div 框中有一个img 元素,它上面有一个伪元素(即::before)。我现在想让该图像以与伪元素相同的方式缩放。以便伪保持在与现在放置的位置相同的位置(屏幕宽度为 375px)。不知道该怎么做。有人可以帮我吗?

<div class="image-box">
    <img class="image-box__image" src="assets/image.png">
</div>
.image-box {
    position: relative;
    &::before {
        content: "";
        position: absolute;
        width: 8.25em;
        height: 8.25em;
        background: tomato;
        border-radius: 50%;
        left: calc(50% - 4.5em);
        top: -5px;
    }
    &__image {
    width: 50%;
    transform: translateX(50%); 
    }
}

提前致谢!

【问题讨论】:

  • 你能链接一张你想要的图片吗?
  • @CharlesLavalard 这真的重要吗? :D 它应该不适用于任何图像吗?
  • 是的,我的意思是我不明白你想要达到什么目的
  • 你想要图像,填充伪元素吗?
  • @CharlesLavalard 嗯。有一个图像。后面有一个红色圆圈(伪)。在设置为 375px 的屏幕宽度上,我将它(那个伪)放置在它应该放置在更大屏幕上的方式上,可以这么说。目前它只是以错误的方式扩展。移动并做我不希望它做的事情

标签: css image sass responsive-design pseudo-element


【解决方案1】:

如果您希望伪元素进行缩放,则需要使用流体单位。 注意下面的方法使用了css属性aspect-ratiothis property isn't fully supported yet

我们如何实现响应式循环:

  • 圈子的width 使用% 而不是em
  • 使用aspect-ratio: 1/1 使高度等于宽度
  • 更改left 属性
  • 添加transform 以使圆圈居中

.image-box {
  position: relative;
}

.image-box::before {
    content: "";
    position: absolute;
    width: 12.5%;
    aspect-ratio: 1/1;
    background: tomato;
    border-radius: 50%;
    left: 50%;
    transform: translateX(-50%);
    top: -5px;
    z-index: 2;
}

.image-box__image {
    width: 50%;
    transform: translateX(50%); 
}
<div class="image-box">
    <img class="image-box__image" src="https://source.unsplash.com/random/400x300">
</div>

【讨论】:

  • 还有其他非实验性的方法吗?
  • 我猜你也可以使用vw,但它会带来它自己的问题
  • 所以要么这样要么那样,这两种方式。对吗?
  • 这些是我能想到的你的实际标记,使用不同的标记你也可以使用填充技巧来获得一个完美的圆圈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
相关资源
最近更新 更多