CSS:如何将列表元素与左对齐文本对齐?

时间:2017-04-06 15:37:08

标签: css

我试图在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;
&#13;
&#13;

4 个答案:

答案 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;

&#13;
&#13;
.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;
&#13;
&#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>