You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决图片容器的::before伪元素显示在图片上方的问题

问题修复方案

问题原因

  • 拼写错误:.main::before 规则中position属性值拼写错误,absoulte为错误写法,正确应为absolute,导致定位规则不生效。
  • 层叠顺序异常:绝对定位元素的默认层级高于普通流内的<img>元素,因此伪元素会默认覆盖在图片上方。

修复后的代码

HTML

<div class='main'>
 <img src="imgg.png">
</div>

CSS

.main{
  height:150px;
  width:150px;
  margin:0 auto;
  position:relative;
  margin-top:1rem;
}
img{
  width:100%;
  height:100%;
  object-fit: cover; /* 替换原无效的background相关属性,实现图片填充容器的效果 */
  border-radius:50%;
}
.main::before{
  display:block;
  content:"";
  width:100%;
  height:100%;
  position:absolute; /* 修正拼写错误 */
  z-index: -1; /* 新增:降低伪元素层级,置于图片下方 */
  top:-1rem;
  right:-1rem;
  background-color:red;
  border-radius:50%;
}

补充说明

你原代码中给<img>设置的background-size、background-repeat属性仅对元素的背景图生效,<img>作为替换元素,需要使用object-fit属性才能实现图片自适应填充容器的效果。

内容的提问来源于stack exchange,提问作者mujtaba hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:45:04