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

如何让::before伪元素内的图片适配1em×1em容器不溢出?

解决伪元素中Favicon无法缩放至1em×1em的问题

问题核心

用content: url()直接引入图片时,图片会固定保持原始尺寸,设置width/height无法触发缩放,object-fit也对这种引入方式无效,只能通过裁剪处理,没法实现完整缩放需求。

可行解决方案

把图片作为伪元素的背景图来实现,通过background-size精准控制缩放效果,具体代码修改如下:

修改后的CSS代码

div#snippet {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(200,200,200,0.3);
}

a#l2020-link {
  color: blue;
  background-color: lightgrey;
  position: absolute;
  bottom: 10px;
  right: 10px;
  border: 0px solid grey;
  border-radius: 3px;
  padding: 3px;
  display: flex;
  flex-direction: row; /* 修正原代码拼写错误:flex-direcion → flex-direction */
  align-items: center; /* 让图标与文字垂直居中对齐 */
  gap: 4px; /* 图标和文字间增加间距,提升视觉舒适度 */
}

a#l2020-link::before {
  content: ""; /* 清空原content的图片引入 */
  width: 1em;
  height: 1em;
  display: inline-block;
  background-image: url(https://www.lampe2020.de/favicon.ico);
  background-size: contain; /* 保持图片比例,完整显示在容器内 */
  background-repeat: no-repeat;
  background-position: center;
}

关键说明

  1. 替换content: url()为背景图方式,才能通过background-size实现图片缩放
  2. 若不需要保持图片比例,可将background-size改为100% 100%,强制图片填满1em×1em容器
  3. 修正原代码中flex-direction的拼写错误,确保flex布局正常生效

对应HTML代码(无需修改)

<div id="snippet">
  <!-- 代码输入框和预览iframe放在这里 -->
  <a href="https://www.lampe2020.de/" id="l2020-link">Lampe2020.de</a>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:15:41