如何使用CSS实现列表图标及其内容的居中对齐
自定义图标列表对齐实现方案
问题场景
复刻网站时,使用自定义图标作为列表项前缀,无法实现图标与对应文本的居中对齐。
- 当前效果:

- 期望效果:

原有实现代码如下:
#container-txt > ul > li { color: var(--terciary-color); font-weight: 700; list-style-position: inside; list-style-image: url(./assets/Checkmark.svg); margin-bottom: 0.3rem; }
<main class="intro"> <div id="container-txt"> <h1>Share your unfiltered<br>thoughts. Get paid.</h1> <p class="paragraph">Spense is an open platform for individuals to share their unfiltered thougths.<br>Discuss the topics you love, and get paid for doing <em>just</em> that.</p> <ul> <li>Receive 99% off the earnings.</li> <li>Get paid via Debit Card, ACH or PayPal.</li> <li>Withdraw your earnings anytime.</li> </ul> </div> </main>
问题原因
原生list-style-image属性对图标位置的可控性极低,没有提供调整图标与文本对齐关系的属性,即使设置list-style-position: inside也无法解决垂直偏移问题。
修复代码
弃用list-style-image方案,通过列表项伪元素挂载自定义图标,配合flex布局实现居中对齐,HTML结构无需修改,替换CSS即可:
/* 清除列表默认样式 */ #container-txt > ul { list-style: none; padding-left: 0; } #container-txt > ul > li { color: var(--terciary-color); font-weight: 700; margin-bottom: 0.3rem; /* flex布局实现图标与文本垂直居中 */ display: flex; align-items: center; gap: 0.6rem; /* 按需调整图标和文本的间距 */ } /* 伪元素挂载自定义对勾图标 */ #container-txt > ul > li::before { content: ""; width: 18px; /* 替换为实际图标尺寸 */ height: 18px; /* 替换为实际图标尺寸 */ background: url(./assets/Checkmark.svg) no-repeat center / contain; flex-shrink: 0; /* 避免图标被挤压变形 */ }
如果对齐存在细微偏差,可通过给伪元素添加小幅margin值微调位置即可。
内容的提问来源于stack exchange,提问作者Vitor
相关产品推荐
相关产品推荐

