萬盛學電腦網

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

CSS列表樣式簡寫屬性:list-style綜合應用與最佳實踐

list-style 簡寫屬性語法

list-style: <list-style-type> || <list-style-position> || <list-style-image>;

/* 順序任意,缺省值由瀏覽器默認填充 */
list-style: square inside url(bullet.png);
list-style: disc outside;           /* 等同於 list-style-type: disc; list-style-position: outside; */
list-style: none;                   /* 移除所有列表標記,常用於導航/重置 */

三個子屬性詳細說明

屬性常用值說明
list-style-typedisc、circle、square、decimal、lower-alpha、none標記類型:實心圓/空心圓/方塊/數字/字母/無
list-style-positionoutside(默認)、inside標記相對內容框位置:外側/內側
list-style-imageurl(...)、none自定義圖片標記,建議配合::marker偽元素現代化替代

現代最佳實踐:拋棄圖片標記,擁抱 ::marker

/* 傳統圖片標記痛點:尺寸不可控、高清屏模糊、無法著色 */
ul.legacy { list-style-image: url(bullet.png); }

/* 現代方案:純CSS繪製,無限縮放、可動畫、可變色 */
ul.modern {
  list-style: none;                 /* 先清除默認 */
  padding-left: 1.5em;              /* 預留標記空間 */
}
ul.modern li::marker {
  content: "▸";                     /* Unicode字符或emoji */
  color: #1890ff;                   /* 任意顏色 */
  font-size: 1.2em;                 /* 獨立縮放 */
  /* 甚至可以用SVG data URI */
  /* content: url("data:image/svg+xml,..."); */
}

/* 數字列表自定義計數器 */
ol.steps {
  list-style: none;
  counter-reset: step;
}
ol.steps li::marker {
  content: "Step " counter(step) " ";
  counter-increment: step;
  font-weight: 600;
  color: #096dd9;
}

避坑指南

  1. 不要混用簡寫與分屬性:list-style: square; list-style-image: url(x.png); 後者會覆蓋前者的type。
  2. 重置樣式表必須包含:ul, ol { list-style: none; padding: 0; margin: 0; }
  3. 巢狀列表縮進:使用padding-left: 1.5em而非margin,保持語義結構。
  4. 無障礙:list-style: none會導致屏幕閱讀器不識別列表,需添加role="list"或保留list-style-type: disc配合::marker { color: transparent }視覺隱藏。

總結:優先使用list-style: none配合::marker偽元素,實現零圖片、可維護、無障礙友好的列表樣式。簡寫屬性list-style適合快速原型,生產環境建議拆分聲明以便覆蓋與主題切換。

copyright © 萬盛學電腦網 all rights reserved