如何用HTML和CSS实现列表项自动换行且无需<br>标签
列表自动换行与容器居中调整方案
核心修改点
- 将
<ul>的外边距设置为margin: 50px auto,实现容器整体居中 - 给
<li>添加text-align: left,让列表项内文本左对齐(默认自动换行,无需<br>)
修改后的完整代码
CSS
.container h1 { margin: 50px; text-align: center; font-size: 2em; font-weight: bold; color: white; } .container h2 { margin: 50px; text-align: center; font-size: 2em; font-weight: bold; color: #0047FF; text-decoration: underline; } .container ul { display: block; margin: 50px auto; /* 上下保留50px边距,左右自动居中 */ text-align: center; max-width: 35%; font-size: 1.5em; color: white; } ul li { list-style: inside; margin-bottom: 2em; text-align: left; /* 列表项文本左对齐,自动换行 */ }
HTML(无需修改)
<div class="container"> <h1>FREQUENTLY ASKED QUESTIONS</h1> <ul> <li>Learn to plan and set your goals so you get more done in less time.</li> <li> Discover the #1 way to create to-do lists to dramatically improve your daily performance and productivity. </li> </ul> </div>
关键说明
- 容器居中原理:块级元素设置宽度(或max-width)后,
margin: 0 auto会让浏览器自动分配左右边距,实现水平居中,这里保留了上下50px的边距。 - 自动换行机制:HTML文本默认会根据容器宽度自动换行,完全不需要手动插入
<br>标签,只要容器有明确的宽度限制(这里是max-width:35%),文本就会自动折行。 - 文本对齐优化:给
<li>设置text-align: left,可以让列表项内的文本左对齐,同时<ul>整体保持居中,兼顾布局美观和可读性。
内容的提问来源于stack exchange,提问作者Álax ϟ
相关产品推荐
相关产品推荐

