我想将我的菜单(这些红色块)对齐到这样的中心:http://i.imgur.com/KDLpjbW.jpg
所以我试着将它与:
对齐HTML
<div id="main">
<nav class="menu">
<ul>
<li><a href="#1">first red block</a></li>
<li><a href="#2">second red block</a></li>
<li><a href="#3">third red block</a></li>
<li><a href="#4">last red block</a></li>
<ul>
</nav>
</div>
CSS
nav.menu {
background: none;
}
nav.menu ul li {
width: 200px;
background: red;
display: inline-block;
margin-right: 33px;
}
nav.menu ul li:last-child {
margin-right: 0;
}
nav.menu a {
line-height: 70px;
}
nav.menu ul {
width: 100%;
}
#main
{
border: 1px solid blue;
margin: auto;
width: 900px;
}
}
但结果如下: http://i.imgur.com/lriGoFm.jpg
我不知道为什么。外部元素具有900px宽度,每个红色块具有200px(4x 200 = 800 ... 100px的可用空间),并且除了最后一个li元素之外,红色块的边缘右边是33px。所以必须有1px的可用空间。
那么为什么最后一个红色块跳出队列? :/
答案 0 :(得分:0)
您应该将 CSS flex属性与justify-content: space-between一起使用。
这里我留下片段:
#main {
border: 1px solid blue;
margin: auto;
width: 900px;
}
nav.menu {
width: 100%;
}
nav.menu ul {
margin: 0;
padding: 0;
width: 100%;
/* this makes the magic ************/
display: flex;
justify-content: space-between;
/***********************************/
}
nav.menu ul li {
width: 200px;
background: red;
text-align: center;
display: inline-block;
}
nav.menu a {
line-height: 70px;
}
<div id="main">
<nav class="menu">
<ul>
<li><a href="#1">first red block</a></li>
<li><a href="#2">second red block</a></li>
<li><a href="#3">third red block</a></li>
<li><a href="#4">last red block</a></li>
</ul>
</nav>
</div>
答案 1 :(得分:0)
*{margin:0;padding:0;box-sizing:border-box}
nav.menu {
width: 900px; /*gave it fixed for demo purpose */
margin:0;
background: none;
}
.menu ul {
font-size: 0; /* when child elements are inline-block, they get some extra margin, to remove it, we give parent element font-size:0; or make child elements float;*/
margin: 0;
padding: 0;
width:100%;
}
.menu ul li {
width: 200px;
background: red;
display: inline-block;
margin-right: 33px;
font-size: 14px; /* as parent had font-size:0; give a new font-size value to view text*/
}
.menu ul li:last-child {
margin-right: 0;
}
nav.menu a {
display: block;
color: #fff;
text-align: center;
line-height: 70px;
}
#main {
border: 1px solid blue;
margin: auto;
width: 900px;
}
&#13;
<nav class="menu">
<ul>
<li><a href="#1">first red block</a></li>
<li><a href="#2">second red block</a></li>
<li><a href="#3">third red block</a></li>
<li><a href="#4">last red block</a></li>
</ul> <!-- your tag wasn't closed, hence last child wasn't working -->
</nav>
&#13;