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

如何使CSS伪元素在其基础元素内正确居中?

让CSS伪元素在父圆形中居中的几种方法

针对你遇到的伪元素无法在主圆形中居中的问题,这里有几种实用的解决方案,结合你的代码示例逐一说明:

方法1:绝对定位 + margin:auto

利用绝对定位的特性,将伪元素的上下左右都设为0,再通过margin:auto实现自动居中,无需依赖元素具体尺寸:

.first::after{
    content: '';
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background-color: rgb(78, 78, 78);
    position: absolute;
    /* 新增居中代码 */
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

方法2:绝对定位 + 负margin

已知伪元素和父元素的尺寸时,通过top:50%、left:50%将伪元素左上角移到父元素中心,再用负margin拉回自身一半尺寸:

.first::after{
    content: '';
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background-color: rgb(78, 78, 78);
    position: absolute;
    /* 新增居中代码 */
    top: 50%;
    left: 50%;
    margin-top: -35px; /* 自身高度的一半 */
    margin-left: -35px; /* 自身宽度的一半 */
}

方法3:绝对定位 + transform: translate

这是最灵活的方法,无需知道元素具体尺寸,translate(-50%, -50%)会基于伪元素自身尺寸计算偏移:

.first::after{
    content: '';
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background-color: rgb(78, 78, 78);
    position: absolute;
    /* 新增居中代码 */
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

方法4:父元素启用Flex布局

直接给父元素添加Flex属性,利用Flex的居中特性让伪元素自动居中,无需定位:

.first{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: rgb(202, 202, 202);
    cursor: pointer;
    box-shadow: 0 0 6px 1px #e8eef6;
    position: relative;
    /* 新增Flex布局 */
    display: flex;
    justify-content: center;
    align-items: center;
}

.first::after{
    content: '';
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background-color: rgb(78, 78, 78);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:55:31