【问题标题】:How to center an unordered list如何使无序列表居中
【发布时间】:2021-10-19 18:24:29
【问题描述】:

我现在已经尝试了很多次,但我不知道如何将我的无序列表放在我的 div 中间。

1:描述它现在的样子 2:描述我希望它的样子

HTML:

 <div id="wrapper">
    <div class="container">
    <img src="flower.jpg"/>
    </div>
    <div class="header">
        <ul>
            <li><a href="default.asp">Home</a></li>
            <li><a href="news.asp">News</a></li>
            <li><a href="contact.asp">Contact</a></li>
            <li><a href="about.asp">About</a></li>
        </ul>
    </div>

CSS:

#wrapper {
    position:absolute;
    background-color: white;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
}

img {
    width: 100%;
    height: 100%; 
    display: block;
}

.header {
    width: 100%;
    height: 100px;
    background-color: green;
}

.header a {
    color: black;
    text-decoration: none;
    margin: 50px;
    padding: 10px;
    font-size: 40px;
    text-align: center;
}

ul {
    list-style-type: none;
    position: absolute;
}

li {
  float: left;
}

我做错了什么?我已经在多个元素中尝试过这些:

  • 位置:相对/绝对
  • 文本对齐:居中
  • 边距
  • 填充
  • 显示:内联

感谢您的帮助

【问题讨论】:

标签: html css


【解决方案1】:

您可以使用flex 做到这一点,如下所示:

ul {
  display: flex;
  flex-direction: row;
  justify-content: center;
  list-style-type:none;
}

您也可以尝试为justify-content 属性设置space-around 值,并且项目将在它们之前、之间和之后有空格。

下面是工作示例:https://jsfiddle.net/tLc9zmoy/26/

【讨论】:

  • 我选择了环绕。谢谢!
【解决方案2】:

您可以更改 ul 元素的样式以匹配以下代码:

ul {
 list-style-type: none;
 position: absolute;
 left: 0;
 right: 0;
 display: flex;
 justify-content: center;
}

【讨论】:

    【解决方案3】:

    您可以通过flex 实现此目的:

    .header {
        display: flex;
        width: 100%;
        height: 100px;
        background-color: green;
        justify-content: center;
    }
    

    注意:您还可以更改 justify-content 的值。关于 flex 和不同属性的一个很好的解释是:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    【讨论】:

      【解决方案4】:
      ul {
        display: flex;
        justify-content:center;
        text-align: center;
        list-style-type:none;
        width:80%;//depending on how wide you want it and note justify center wont work 
         unless you specify width on most cases
      
      }
      

      【讨论】:

        猜你喜欢
        • 2013-10-26
        • 1970-01-01
        • 2018-07-30
        • 2017-12-13
        • 2017-12-09
        • 2012-11-14
        • 1970-01-01
        • 2012-12-18
        相关资源
        最近更新 更多