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

查询规定CSS background-position属性50%定位行为的标准文档

CSS background-position 50% 定位规则的标准来源

这个定位行为是由CSS Backgrounds and Borders Module规范定义的,目前主流浏览器遵循的是Level 3版本,后续的Level 4版本也延续了这一核心规则。

核心计算逻辑

对于background-position的百分比值,规范里明确了计算方式:

背景图像的偏移量 = (容器对应维度的尺寸 - 背景图像对应维度的尺寸) × 百分比数值

拿你的示例拆解一下:

  • 容器宽度为9px,背景图像宽度为4px,两者的尺寸差是5px
  • 水平方向偏移量 = 5px × 50% = 2.5px

为什么会出现左右间距不等的情况?

你设置了image-rendering: pixelated,这个属性会强制图像对齐到整数像素网格。当计算出的偏移量是小数(比如这里的2.5px)时,浏览器会按照规范中的像素对齐规则向上取整为3px——最终图像从容器左侧3px的位置开始渲染,到3px+4px=7px的位置结束,右侧自然就剩下9px-7px=2px的间距。

可复现的示例代码

#a { 
    background-position: 50% 50%; 
    background-image: linear-gradient(red,red); 
    width: 9px; 
    height: 10px; 
    image-rendering: pixelated; 
    background-color: black; 
    background-repeat: no-repeat; 
    background-size: 4px 6px; 
} 
<div id="a"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:47:32