ul 与 css 的动态居中对齐

dynamic centered alignment of a ul with css

我正在从以 ul li 格式打印的数据库中提取数据。由于数据不同,我们可能有 2 个 li 项目,或者我们可能有 10 个谁知道呢。

将宽度会发生变化的 ul 或 div 居中的最佳方法是什么?我知道要居中 div 或 ul 我会使用以下内容:

#name, ul {
 width:200px; /*set certain width */
 margin:0 auto; /* center div */
 display:block /* play friendly with the existing layout */
}

我的问题是数据 div 可能是 200 像素或超过 200 像素,因此它不会真正居中,因为 div 居中对齐是基于宽度。

如有任何帮助,我们将不胜感激。

这是一种可以将具有动态内容长度的 ul 居中的方法。

您可以将 ul 包裹在 div 中,并将 DIV 上的 CSS 属性 设置为

.wrapper{
  display:table;
  margin: 0 auto;
}

无论 div 的宽度如何,这都会在 div 内居中对齐 ul,您可以看下面的示例:

Codepen Link http://codepen.io/nadirlaskar/pen/RKbBpM

.wrapper{
  display:table;
  margin: 0 auto;
  background-color:yellow;
}

ul{
  background-color:red;
}

li{
  background-color:blue;
}
<div class="wrapper">
  <ul>
    <li>Item 1</li>
    <li>Item 2  is now large</li>  
  </ul>  
</div>