我试图在div中居中对齐列表,但保持文本左对齐。
所以,我希望所有子弹垂直排列(左对齐),但整个列表本身应该位于中心,如下例中的段落所示:
.container { width: 600px; padding: 2em; background: #eee; }
.align-center { text-align: center; }

<div class="container">
<p class="align-center">Center Align Test</p>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Finally, the third and final element</li>
</ul>
</div>
&#13;
答案 0 :(得分:5)
将ul
设为inline-block
元素并将其置于中心位置。然后左对齐li
。
.container {
width: 600px;
padding: 2em;
background: #eee;
text-align: center;
}
ul {
display: inline-block;
text-align: left;
}
.align-center {
text-align: center;
}
<div class="container">
<p class="align-center">Center Align Test</p>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Finally, the third and final element</li>
</ul>
</div>
..或使用 Flexbox
.container {
width: 600px;
padding: 2em;
background: #eee;
display: flex;
flex-direction: column;
align-items: center;
}
.align-center {
text-align: center;
width: 100%;
}
<div class="container">
<p class="align-center">Center Align Test</p>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Finally, the third and final element</li>
</ul>
</div>
答案 1 :(得分:0)
我建议将text-align:center
添加到容器div
,以便ul
居中。然后,您需要将display:inline-block
应用于ul
,以便它不占用整个水平空间。最后,将text-align:left
添加到ul
,以便center
不会根据需要从父级继承。
.container { width: 600px; padding: 2em; background: #eee; text-align:center}
.align-center { text-align: center; }
ul {display:inline-block; text-align:left}
<div class="container">
<p class="align-center">Center Align Test</p>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Finally, the third and final element</li>
</ul>
</div>
答案 2 :(得分:0)
将text-align: center;
添加到容器中,使ul
成为inline-block
并提供ul
text-align: left;
.container { width: 600px; padding: 2em; background: #eee; text-align: center;}
.align-center { text-align: center; }
ul { display: inline-block; text-align: left;}
&#13;
<div class="container">
<p class="align-center">Center Align Test</p>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Finally, the third and final element</li>
</ul>
</div>
&#13;
答案 3 :(得分:0)
只需使用 flex 容器。
.flex-container
{
display:flex;
justify-content:center;
text-align: left;
}
<div class="flex-container">
<ul>
<li>Left Aligned #1</li>
<li>Left Aligned #2</li>
<li>Left Aligned #3</li>
</ul>
</div>