首页 > 解决方案 > 将 html ul 完全居中在容器中

问题描述

我有这个无序列表,我想垂直显示它,并让它在父容器内完全居中。我设法让它垂直显示并以 x 轴为中心,但不在 y 轴上。“垂直对齐:中间;” 似乎没有做我想要的。

考虑这个 html 代码:

div {
  margin: auto;
  width: 90%;
  height: 200px;
  background-color: lightblue;
}

ul {
  list-style: none;
  height: 100%;
  width: 100;
  padding: 0;
  text-align: center
}

ul li {
  display: inline;
  margin-right: 20px;
  vertical-align: middle;
}
<div>
  <ul>
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
  </ul>
</div>

标签: htmlcss

解决方案


要在 y 轴上垂直对齐,请将以下给定的 css 添加到 ul:

  display:flex;
  justify-content:center;
  align-items:center;

width:100;从 ul 标签中删除。

演示

div {
  margin: auto;
  width: 90%;
  height: 200px;
  background-color: lightblue;
}

ul {
  list-style: none;
  height: 100%;
  padding: 0;
  display:flex;   /*add this */
  justify-content:center; /*add this */
  align-items:center; /*add this */
  
  text-align: center
}

ul li {
  display: inline;
  margin-right: 20px;
  vertical-align: middle;
}
<div>
  <ul>
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
  </ul>
</div>


推荐阅读