CSS 列表样式
CSS 列表样式详解 · 难度:入门 · +10XP
CSS 列表样式详解
CSS 提供了强大的列表样式控制能力。通过 list-style 系列属性,你可以自定义无序列表和有序列表的标记样式、位置,甚至用自定义图片或 emoji 替代默认标记。
列表标记类型 list-style-type
list-style-type 设置列表项标记的外观:
/* 无序列表标记 */
ul.disc { list-style-type: disc; } /* 实心圆(默认) */
ul.circle { list-style-type: circle; } /* 空心圆 */
ul.square { list-style-type: square; } /* 实心方块 */
ul.none { list-style-type: none; } /* 无标记 */
/* 有序列表标记 */
ol.decimal { list-style-type: decimal; } /* 1, 2, 3 */
ol.decimal-leading-zero { list-style-type: decimal-leading-zero; } /* 01, 02 */
ol.lower-alpha { list-style-type: lower-alpha; } /* a, b, c */
ol.upper-alpha { list-style-type: upper-alpha; } /* A, B, C */
ol.lower-roman { list-style-type: lower-roman; } /* i, ii, iii */
ol.upper-roman { list-style-type: upper-roman; } /* I, II, III */
ol.lower-greek { list-style-type: lower-greek; } /* alpha, beta */
ol.cjk-ideographic { list-style-type: cjk-ideographic; } /* 一, 二, 三 */
自定义标记位置 list-style-position
/* inside: 标记在列表项内部(内容缩进受影响) */
ul.inside {
list-style-position: inside;
}
/* outside: 标记在列表项外部(默认,标记悬挂在外) */
ul.outside {
list-style-position: outside;
}
使用自定义图片作为标记 list-style-image
ul.custom-marker {
list-style-image: url('/images/checkmark.svg');
}
list-style 简写
/* 顺序: type position image */
ul {
list-style: square inside;
}
ol {
list-style: lower-roman outside;
}
/* 去掉所有列表样式 */
nav ul {
list-style: none; /* 导航栏常用 */
}
使用 ::marker 伪元素自定义标记
::marker 伪元素可以更精细地控制列表标记的样式:
li::marker {
color: #3498db;
font-weight: bold;
font-size: 1.2em;
}
/* 使用 content 更改标记内容 */
li.step::marker {
content: "Step " counter(list-item) ": "; /* 仅 Firefox 支持 */
color: #e74c3c;
}
自定义列表标记(兼容方案)
使用 ::before 伪元素可以在更多浏览器中实现自定义标记:
ul.custom {
list-style: none;
padding-left: 0;
}
ul.custom li {
padding-left: 1.5em;
position: relative;
}
ul.custom li::before {
content: "\2713"; /* 勾选符号 */
position: absolute;
left: 0;
color: #2ecc71;
font-weight: bold;
}
列表样式速查表
| 属性 | 作用 | 常用值 |
|---|---|---|
| list-style-type | 标记类型 | disc / circle / square / decimal / none |
| list-style-position | 标记位置 | inside / outside |
| list-style-image | 自定义标记图片 | url() / none |
| list-style | 简写属性 | square inside url() |
???? 练习
- 创建一个无序列表,分别测试 disc、circle 和 square 标记样式
- 用有序列表创建一个大纲结构,使用不同层级的编号样式
- 使用 ::before + content 创建自定义的 emoji 标记列表
- 用 list-style: none 去除导航栏列表的默认样式
- 对比 list-style-position: inside 和 outside 的缩进差异