萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS ul li 背景圖標定位兩大場景:容器級 vs 項目級的選擇準則

兩種典型場景

場景 A:容器級背景圖(連續長條圖標/裝飾線)

特徵:圖標/裝飾線高度超過單行,貫穿整個列表,或為連續垂直線條。

定位策略:背景圖設在 <ul> 容器上,background-position: left top 或 left center,no-repeat 或 repeat-y。

.test1 {
  width: 100px; height: 265px;
  background: url(li.jpg) no-repeat scroll 0 8px;  /* 容器級背景 */
}
.test1 li {
  padding-left: 30px;  /* 騰出左側空間給背景圖 */
  line-height: 27px;
  list-style-type: none;
}

容器級背景圖示例

場景 B:項目級背景圖(獨立小圖標:圓點、箭頭、勾選)

特徵:每行前獨立的小圖標(•、▶、✓、icon),大小固定,與行高對齊。

定位策略:背景圖設在 <li> 上,background-position: left center(垂直居中),no-repeat。

.test1 li {
  padding-left: 15px;  /* 圖標寬度 + 間距 */
  background: url(icon_fk.gif) no-repeat scroll 1px 8px;  /* 項目級背景 */
  line-height: 22px;
  list-style-type: none;
}

項目級背景圖示例

決策流程圖

需要列表項前置圖標/裝飾?
├─ 圖標是否為連續垂直線條/超高裝飾圖?
│   ├─ 是 → 容器級背景(ul)+ li padding-left 騰位
│   └─ 否 → 獨立小圖標?
│         ├─ 是 → 項目級背景(li)+ background-position: left center
│         └─ 否 → 考慮 ::before 偽元素 + content: "" + 寬高 + background
└─ 無圖標 → list-style-type 或 CSS 計數器

現代最佳實踐:偽元素替代背景圖

優勢:不佔用 background 屬性(留給容器背景色/圖)、可動畫、可變色、無額外請求(配合 SVG Data URI/字體圖標)。

通用圖標偽元素模板

.icon-list { list-style: none; }
.icon-list li {
  position: relative;
  padding-left: 1.5em;  /* 圖標空間 */
}
.icon-list li::before {
  content: "";
  position: absolute;
  left: 0; top: 50%;
  width: 1em; height: 1em;
  margin-top: -0.5em;  /* 垂直居中 */
  background: currentColor;  /* 繼承文字顏色 */
  mask: url(icon.svg) center/contain no-repeat;  /* SVG 遮罩,可變色 */
  -webkit-mask: url(icon.svg) center/contain no-repeat;
}

/* 特定圖標 */
.icon-list.arrow li::before { mask-image: url(arrow.svg); }
.icon-list.check li::before { mask-image: url(check.svg); }

Font Icon 方案

.icon-list li::before {
  font-family: "iconfont";
  content: "\e001";  /* 字形碼位 */
  position: absolute;
  left: 0; top: 50%;
  transform: translateY(-50%);
  font-size: 1em;
  color: inherit;
}

常見坑位與避坑指南

坑點現象解決
背景圖垂直居中失效line-height 不固定、多行文字用偽元素 + top:50% + transform:translateY(-50%)
高 DPI 模糊位圖圖標在 Retina 下模糊用 SVG / @2x 圖 + background-size / Font Icon
圖標與文字基線對齊vertical-align 不生效偽元素 absolute 定位 + 容器 relative
RTL 語言鏡像阿拉伯語/希伯來語下圖標位置錯誤用邏輯屬性 padding-inline-start、inset-inline-start

總結

容器級背景(ul)適合連續裝飾線,項目級背景(li)適合獨立小圖標——這是核心判斷標準。現代開發強烈建議遷移至 ::before 偽元素 + SVG Mask / Font Icon 方案,獲得更強的樣式控制力、無障礙友善性與維護彈性。理解兩種傳統背景定位模式,有助於閱讀遺留代碼與進行平滑重構。

copyright © 萬盛學電腦網 all rights reserved