【问题标题】:Center html ul completely in container [duplicate]将html ul完全居中在容器中[重复]
【发布时间】:2020-01-09 13:58:23
【问题描述】:

我有这个无序列表,我想垂直显示它并使其在父容器内完全居中。我设法让它垂直显示并以 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>

【问题讨论】:

  • 我认为当您说垂直时,您的意思是水平。此外,width: 100; 无效。需要一个单位
  • Vertically center ul in div 的可能重复项以及通过搜索 SO 找到的大量相同问题。
  • 是的,感谢您指出这一点。

标签: html css


【解决方案1】:

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

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

并从 ul 标记中删除 width:100;

演示

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>

【讨论】:

    【解决方案2】:

    您可以将display: flex 用于 div,将margin: auto 用于 ul。并从 ul 中删除 heightwidth 规则。这是工作的Fiddle

    <div>
      <ul>
        <li>List Item 1</li>
        <li>List Item 2</li>
        <li>List Item 3</li>
      </ul>
    </div>
    
    div {
        display: flex;
        margin: auto;
        width: 90%;
        height: 200px;
        background-color: lightblue;
    }
    
    ul {
        margin: auto;
        list-style: none;
        padding: 0;
        text-align: center
    }
    
    ul li {
        display: inline;
        margin-right: 20px;
        vertical-align: middle;
    }
    

    【讨论】:

    • 请在您的问题中发布您的代码,而不是 jsFiddle
    【解决方案3】:

    要垂直对齐,您可以使用line-height。 在 div 标签中使用 line-height 而不是 height。

    div {
      margin: auto;
      width: 90%;
      line-height: 200px;  /*change this */
      background-color: lightblue;
    }
    

    div {
      margin: auto;
      width: 90%;
      line-height: 200px;
      background-color: lightblue;
    }
    
    ul {
      list-style: none;
      height: 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>

    【讨论】:

    • 我会说使用行高是一种不好的做法。因为我们可能需要覆盖该父 div 下的段落/内容的行高。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多