如何将无序列表居中显示

3

我已经尝试了多次,但是我无法弄清如何将我的无序列表放在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;
}

我做错了什么?我在多个元素中试过以下内容:

  • position: relative/absolute (相对位置/绝对位置)
  • text-align: center(文本居中)
  • margin(外边距)
  • padding(内边距)
  • display: inline(行内显示)

感谢帮助 <3


1
Flexbox是你的好朋友 ;) - BenM
我会调查一下!从来没听说过 :D - HTML_Newbie
1
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ - BenM
4个回答

4
您可以更改ul元素的样式以匹配以下代码:
ul {
 list-style-type: none;
 position: absolute;
 left: 0;
 right: 0;
 display: flex;
 justify-content: center;
}

4
你可以使用 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

}

3

你可以使用flex来实现这个功能,像这样:

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

你还可以尝试将justify-content属性设置为space-around值,这样项目之间就会有前、中、后的空间。

以下是一个工作示例:https://jsfiddle.net/tLc9zmoy/26/


1
我选择了 space-around。谢谢! - HTML_Newbie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接