【问题标题】:Can a CSS ::after pseudo-element be fitted to the size of its parent?CSS ::after 伪元素可以适应其父元素的大小吗?
【发布时间】:2021-01-29 14:05:27
【问题描述】:

我想在图像上添加渐变。有没有办法在 CSS 中使用 ::after 元素来做到这一点? 图像的尺寸未知,位置是静态的。

HTML:

<span class="gradient">
    <img src="https://i.stack.imgur.com/uZ2WS.gif">
</span>

CSS:

.gradient img::after{
    content: "";
    background-image: linear-gradient(#000, #ffffff00);
}

有什么方法可以定位这个 ::after 以使其完全适合图像上方?

【问题讨论】:

  • position:relative 然后绝对到伪就可以了。 mix-blend-mode 也可以在没有伪的情况下工作
  • img 不能有 ::after 或 ::before。只有可以有子元素的元素才可以。
  • @connexo 啊,谢谢!将其移至 span 而不是 img 效果很好!

标签: css pseudo-element


【解决方案1】:

position 和 display 可以做到:

span {
  position: relative;
  display: inline-block;
}

span::after {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  content: "";
  background-image: linear-gradient(#000, #ffffff00);
}
<span class="gradient">
    <img src="https://i.stack.imgur.com/uZ2WS.gif">
</span>

mix-blend-mode 和 display 也是:

span {
  display: inline-block;
  background-image: linear-gradient(#000, #ffffff00);
}
img {
  mix-blend-mode: multiply;
}
<span class="gradient">
    <img src="https://i.stack.imgur.com/uZ2WS.gif">
</span>

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多