我试图让这段代码在中间以95%的比例显示导航栏(每面免费提供2.5%)。我在互联网上找到了几种方法,但它们会要求我使用其他风格,我希望保持不变。
#nav ul {
position: fixed;
top: 5px;
width: 100%;
list-style-type: none;
margin: 0;
margin-left: 10%;
padding: 0;
overflow: hidden;
background-color: #ffffff;
}
#nav li {
float: left;
}
#nav li a {
display: block;
color: #0066cc;
text-align: center;
padding: 10px 20px;
text-decoration: none;
}
#nav li a:hover {
background-color: #111;
}
#nav .active {
background-color: #ffffff;
border-top-width: 5px;
border-top-style: solid;
border-top-color: #0066cc;
border-bottom-width: 5px;
border-bottom-style: solid;
border-bottom-color: #0066cc;
}
#nav .inactive {
border-width: 5px;
border-top-style: solid;
border-top-color: #ffffff;
border-top-color: #0066cc;
border-bottom-width: 5px;
border-bottom-style: solid;
border-bottom-color: #0066cc;
}
Html part:
<div id="nav">
<ul>
<li><a class="active" href="../HTML/Home.html">Home</a></li>
<li><a class="inactive" href="../HTML/Shop.html">Shop</a></li>
<li><a class="inactive" href="../HTML/SocialNews.html">Social News</a></li>
<li><a class="inactive" href="../HTML/Gallary.html">Gallary</a></li>
<li><a class="inactive" href="../HTML/CustomerReviews.html">Customer Reviews</a></li>
<li><a class="inactive" href="../HTML/Sponsorship.html">Sponsorship</a></li>
<li><a class="inactive" href="../HTML/Contact.html">Contact</a></li>
<li><a class="inactive" href="../HTML/Cart.html">Cart</a></li>
</ul>
</div>
最佳答案
使用width: 95%; left: 50%; transform: translateX(-50%);
将菜单设置为95%宽度并居中。
然后将display: flex
添加到菜单中,然后将flex: 1 0 0
添加到li
中以拉伸这些元素,以便它们填充菜单。
#nav ul {
position: fixed;
top: 5px;
list-style-type: none;
padding: 0;
overflow: hidden;
background-color: #ffffff;
width: 95%;
display: flex;
left: 50%;
transform: translateX(-50%);
}
#nav li {
flex: 1 0 0;
}
#nav li a {
display: block;
color: #0066cc;
text-align: center;
padding: 10px 20px;
text-decoration: none;
height: 100%;
box-sizing: border-box;
}
#nav li a:hover {
background-color: #111;
}
#nav .active {
background-color: #ffffff;
border-top-width: 5px;
border-top-style: solid;
border-top-color: #0066cc;
border-bottom-width: 5px;
border-bottom-style: solid;
border-bottom-color: #0066cc;
}
#nav .inactive {
border-width: 5px;
border-top-style: solid;
border-top-color: #ffffff;
border-top-color: #0066cc;
border-bottom-width: 5px;
border-bottom-style: solid;
border-bottom-color: #0066cc;
}
<div id="nav">
<ul>
<li><a class="active" href="../HTML/Home.html">Home</a></li>
<li><a class="inactive" href="../HTML/Shop.html">Shop</a></li>
<li><a class="inactive" href="../HTML/SocialNews.html">Social News</a></li>
<li><a class="inactive" href="../HTML/Gallary.html">Gallary</a></li>
<li><a class="inactive" href="../HTML/CustomerReviews.html">Customer Reviews</a></li>
<li><a class="inactive" href="../HTML/Sponsorship.html">Sponsorship</a></li>
<li><a class="inactive" href="../HTML/Contact.html">Contact</a></li>
<li><a class="inactive" href="../HTML/Cart.html">Cart</a></li>
</ul>
</div>