在 :before 或 :after 伪元素中具有固定大小的对象

An object with fixed sizes inside :before or :after pseudo element

我知道我可以做类似的事情:

.container:after {
    content: url("../images/img.png");
    display: inline-block;
    width: 100%;
    height: auto;
}

有没有什么方法可以在不引用图像的情况下实现类似的功能?我需要的是根据父元素(例如.container)的宽度更改其高度的伪元素。与带有 width:100%; height: auto; 的图像非常相似 非常感谢!

来自我对 this related question 的回答:

In the meantime, if you want to be able to resize the :after pseudo-element and the image that's generated, you will need to apply it as a background image instead and — assuming browser support isn't an issue — use background-size along with width and height to scale it (based on the understanding that those properties apply to the pseudo-element box instead).

所以,而不是

content: url("../images/img.png");

使用

background-image: url("../images/img.png");
background-size: cover;

(或 shorthand、background: url("../images/img.png") 0 0 / cover

至于按比例缩放伪元素,我认为您应该可以使用 padding-bottom 技巧来完成此操作。对于比例为 1:2 的图像,padding-bottom: 200% 似乎适用于此示例:

.container {
  border: thick solid;
  margin: 1em;
}

.large.container { width: 100px; }
.small.container { width: 50px; }

.container::after {
  content: '';
  display: block;
  background: url(http://placehold.it/100x200) 0 0 / cover;
  padding-bottom: 200%;
}
<div class="large container"></div>
<div class="small container"></div>