首页 > 解决方案 > 如何对齐在 div 内居中的无序列表?

问题描述

我试过这样。如何在 div 中居中列出项目?

.navsection{
    background-color: cadetblue;
    text-align: center;
}

.navsection ul{
    margin: 0;
    padding: 0;
    list-style: none;
    
    /* display: table;
    margin: 0 auto; */
}
.navsection ul li{
   display: block;
   float: left; 
   
}
.navsection ul li a{
    text-decoration: none;
    color: rgb(116, 4, 26);
    display: inline-block;
    padding: 10px 20px;
    background: rgb(127, 210, 212);
    margin: 5px 2px;
}
<div class="navsection tem clear">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Gallery</a></li>
        </ul>
    </div>
我试图将 ul 标记放在 div 中,然后将其带到中心。所以我使文本对齐中心。但它不起作用。为什么这不起作用?我试图将 ul 标记放在 div 中,然后将其带到中心。所以我使文本对齐中心。但它不起作用。为什么这不起作用?

标签: htmlcss

解决方案


使用flex选择器的规则.navsection。它应该如下所示:

.navsection {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: cadetblue;
}

.navsection{
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: cadetblue;
}

.navsection ul{
    margin: 0;
    padding: 0;
    list-style: none;
    
    /* display: table;
    margin: 0 auto; */
}
.navsection ul li{
   display: block;
   float: left; 
   
}
.navsection ul li a{
    text-decoration: none;
    color: rgb(116, 4, 26);
    display: inline-block;
    padding: 10px 20px;
    background: rgb(127, 210, 212);
    margin: 5px 2px;
}
<div class="navsection tem clear">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Gallery</a></li>
        </ul>
</div>

第二种解决方案(无弹性):

删除选择器中的float: leftand makedisplay: inline-block而不是。display: block.navsection ul li

它应该是这样的:

.navsection ul li{
   display: inline-block;
   /*float: left; */   
}

.navsection{
    background-color: cadetblue;
    text-align: center;
}

.navsection ul{
    margin: 0;
    padding: 0;
    list-style: none;
    
    /* display: table;
    margin: 0 auto; */
}

.navsection ul li{
   display: inline-block;
   /*float: left; */   
}

.navsection ul li a{
    text-decoration: none;
    color: rgb(116, 4, 26);
    display: inline-block;
    padding: 10px 20px;
    background: rgb(127, 210, 212);
    margin: 5px 2px;
}
<div class="navsection tem clear">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Gallery</a></li>
        </ul>
</div>


推荐阅读