伪元素::before背景图不显示的主因是未设content属性且无尺寸;必须设置content: ""、display为block等并指定宽高,同时检查路径、overflow、z-index及background-repeat等。
伪元素 ::before 的背景图片不显示,最常见的原因是它默认是**行内元素且不占空间**——即使设置了 background-image,若没有尺寸、内容或显式布局行为,浏览器不会渲染它。
content
::before 和 ::after 是“生成内容”的伪元素,content 属性是必需的,哪怕只是空字符串。不写 content,整个伪元素根本不会被创建,背景图自然不会出现。
div::before { background-image: url(icon.png); }
✓ 正确写法(显式设为空):
div::before { content: ""; background-image: url(icon.png); }
仅设 content: "" 还不够——空字符串产生的伪元素默认是 display: inline,宽高为 0,背景图无处可画。必须让它“有形”:
display: block(或 inline-block、flex 等)width 和 height(或用 padding、min-height 等撑开)background-size: contain/cover,更需确保容器有明确宽高即使 content 和 display 都对了,仍可能因以下原因看不到背景图:
overflow: hidden,而伪元素定位超出范围position 或 z-index,被其他内容遮挡background-repeat: no-repeat; background-position: center; 排查div::before {
content: "";
display: block;
width: 20px;
height: 20px;
background-image: url("icon.s
vg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}