不用 z-index 把 ::after 放在元素下面的方法

好久没写 CSS 了,我想写个定长定宽的 ::after 放在 <img> 后面做效果,但是塞不到底下,查了下是写 z-index: -1 这种老方法。但是这方法了在套娃的情况下就不行了,直接跑到最下面了,蓝后就查了下,发现可以用 transform 解决。

参考链接:css - Is it possible to set the stacking order of pseudo-elements below their parent element? - Stack Overflow

最顶上被选用的回答就是常见的 z-index: -1,但是有个条件,就是东西都在 <body> 里面,结构大概如下:

<body>
  <div class="a">
    ::after
  </div>
</body>

这样的 -1 才有用。那如果套娃呢?结构如下:

<body>
  <div class="bg">
    <div class="a">
      ::after
    </div>
  </div>
</body>

这时候还用 z-index: -1 的话 ::after 就跑到 .bg 底下了。所以就用了另一个东西:transform-style,把变换方式从平面改成 3D 就可以啦。结构还是上面这套娃,SCSS 如下:

.bg{bgc:#ccc}
.a {
  transform-style: preserve-3d;
  &::after {
    transform: translateZ(-1px);
  }
}

这样 ::after 就会相对往后缩 1px,不就可以跑后面去了,美滋滋。根据 Can I Use 的显示,绝大部分浏览器都兼容的,UC 啥的不清楚,也懒得理,总之就是爽。


20220312 Update:<img> 标签不能用 ::before::after,还有几个标签也不能用,又掉进另一个坑了。原因:

The before and after pseudo-selectors don't insert HTML elements — they insert text before or after the existing content of the targeted element. Because image elements don't contain text or have descendants, neither img:before or img:after will do you any good. This is also the case for elements like <br> and <hr> for the same reason.

——coreyward

简单来说就是 ::before::after 是往元素里面插文字的,但是 <img> 里面没有内容,所以就无效了,<br><hr> 也同理。

不用 z-index 把 ::after 放在元素下面的方法 有 3 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注