如何在HTML列表项(<li>)内实现文本垂直对齐?
Got it, let's sort out that vertical alignment issue in your <li> elements. The core problem here is that your list items have a much larger font size (32px) than the nested <div>s (17px), so the smaller text might sit awkwardly by default. Here are three reliable solutions to get things aligned properly:
1. Use Flexbox (Most Recommended)
Flexbox is the modern, flexible way to handle alignment—works great across all modern browsers and adapts well if your content changes later. Just add display: flex and align-items to your <li> style to control how the inner <div> sits vertically:
<ul> <li style="margin: 0; padding-bottom: 23px; font-size: 32px; display: flex; align-items: center;"> <div style="font-family: 'Arial','sans-serif'; color: black; font-size: 17px;">[%code1%]</div> </li> <li style="margin: 0; padding-bottom: 23px; font-size: 32px; display: flex; align-items: center;"> <div style="font-family: 'Arial','sans-serif'; color: black; font-size: 17px;">[%code2%]</div> </li> </ul>
- Use
align-items: centerto vertically center the<div>inside the<li>. - If you want the small text to align with the baseline of the 32px font (in case your
<li>ever has other text), swapcenterforbaseline.
2. Use vertical-align with Inline-Block
If you prefer not to use flexbox, you can convert the <div> to an inline-block element and use the vertical-align property:
<ul> <li style="margin: 0; padding-bottom: 23px; font-size: 32px;"> <div style="font-family: 'Arial','sans-serif'; color: black; font-size: 17px; display: inline-block; vertical-align: middle;">[%code1%]</div> </li> <li style="margin: 0; padding-bottom: 23px; font-size: 32px;"> <div style="font-family: 'Arial','sans-serif'; color: black; font-size: 17px; display: inline-block; vertical-align: middle;">[%code2%]</div> </li> </ul>
display: inline-blocklets the<div>behave like an inline element for alignment purposes.vertical-align: middlepushes the text to the vertical center of the<li>'s line box.
3. Use line-height (Simple, Limited Use Case)
If your <li>s will only ever contain single-line text, you can set a fixed line-height on the <li> and have the inner <div> inherit it:
<ul> <li style="margin: 0; padding-bottom: 23px; font-size: 32px; line-height: 40px;"> <div style="font-family: 'Arial','sans-serif'; color: black; font-size: 17px; line-height: inherit;">[%code1%]</div> </li> </ul>
- This works best for short, non-wrapping text. If your
<div>content wraps to multiple lines, this method will cause unwanted spacing between lines.
Pick the solution that fits your use case—Flexbox is the most robust option for most scenarios.
内容的提问来源于stack exchange,提问作者user9703003

