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

单选按钮奇数尺寸时::before伪元素无法完全居中问题求助

解决奇数尺寸下单选按钮内部圆点偏移问题

当使用::before伪元素实现单选按钮的选中圆点时,若设置的--size为奇数,内部圆点会出现无法完全居中的情况,且尺寸越小偏移越明显。这是因为奇数像素尺寸下,left:50%、top:50%结合translate: -50% -50%会产生半像素偏移,部分浏览器渲染时无法完美处理,导致视觉上的错位。

修复方案一:用Flex布局实现原生居中

将按钮容器改为Flex布局,直接通过Flex属性让伪元素居中,彻底避免百分比偏移带来的半像素问题:

.input-radio { 
    display: flex;
    gap: 10px;
    height: fit-content;
}

.input-radio-button {
    --Primary-color:#07f;
    display: flex; /* 改为flex容器 */
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    --size:15px;
    width: var(--size,10px);
    height: var(--size,10px);
    font-size: 13px;
    aspect-ratio: 1;
    border: var(--border-length,calc(var(--size,10px) / 7)) var(--Primary-color,#07f) solid;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    background: none;
    flex-grow: 0;
    flex-shrink: 0;
}

.input-radio-button::before { 
    content: "";
    width: 100%;
    aspect-ratio: 1;
    border-radius: 50%;
    background: var(--Primary-color);
    transition: scale .2s .1s;
    /* 移除绝对定位、left/top/translate属性 */
}

修复方案二:用绝对定位+inset:auto实现居中

通过inset: 0和margin: auto让伪元素在容器内自动居中,同样能规避半像素偏移问题,适合需要保留绝对定位的场景:

.input-radio-button::before { 
    content: "";
    /* 可根据需求调整尺寸,比如设为容器的一半 */
    width: calc(var(--size,10px) / 2);
    height: calc(var(--size,10px) / 2);
    border-radius: 50%;
    background: var(--Primary-color);
    position: absolute;
    inset: 0; /* 等同于top/right/bottom/left:0 */
    margin: auto; /* 自动居中 */
    transition: scale .2s .1s;
}

补充说明

原代码中伪元素设置了width:100%,会让它和容器完全重叠,建议配合选中状态添加scale变换(比如未选中时scale(0),选中时scale(0.5)),才能显示出边框+内部圆点的效果:

.input-radio.checked .input-radio-button::before {
    scale: 0.5;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:45:20