HTML:
<nav>
<ul>
<li><a href="Index">Home</a></li>
<li><a href="History">History</a></li>
<li><a href="Appointments">Appointments</a></li>
<li><a href="Contactus">Contact us</a></li>
</ul>
</nav>
CSS:
nav {
position: relative;
margin: auto;
padding: 0;
list-style: none;
width: 100%;
display: center;}
nav ul li {
display: inline;
}
nav ul li a {
display: inline-block;
text-decoration: none;
padding: 5px 0;
width: 100px;
background: #Cc3399;
color: #eee;
float: left;
text-align: center;
border-left: 1px solid #fff;
}
nav ul li a:hover {
background: #a2b3a1;
color: #000
}
基本上,我设法制作了符合我规格的导航栏。但是,它没有居中,它处于垂直位置,但是水平方向离开了,没有靠近页面中心的位置。
答案 0 :(得分:5)
一种解决方案是将inline
替换为inline-block
并将text-align: center
替换为父级(同时display: center
无效css):
nav {
position: relative;
margin: auto;
padding: 0;
list-style: none;
width: 100%;
text-align: center;/*add text align-center*/
}
nav ul li {
display: inline-block;/*replace inline to inline-block*/
}
nav ul li a {
display: inline-block;
text-decoration: none;
padding: 5px 0;
width: 100px;
background: #Cc3399;
color: #eee;
float: left;
text-align: center;
border-left: 1px solid #fff;
}
nav ul li a:hover {
background: #a2b3a1;
color: #000
}
&#13;
<nav>
<ul>
<li><a href="Index">Home</a>
</li>
<li><a href="History">History</a>
</li>
<li><a href="Appointments">Appointments</a>
</li>
<li><a href="Contactus">Contact us</a>
</li>
</ul>
</nav>
&#13;
答案 1 :(得分:0)
由于你已经给予100%的保证金,因为它不会对保证金产生影响。所以尝试给予50%的宽度,它应该有效。 你可以这样改变......
nav
{
position: relative;
margin: auto;
padding: 0;
list-style: none;
width: 50%;
display: center;
}
答案 2 :(得分:0)
要将元素水平居中,此元素需要显示:block;它的宽度应小于100%
这是css,根据你拥有的内容稍作修改
nav {
position: relative;
/*** centers the nav block ****/
margin-left: auto;
margin-right: auto;
width: 80%;
}
nav ul{
padding: 0;
list-style: none;
}
nav ul li {
display: inline;
}
nav ul li a {
display: inline-block;
text-decoration: none;
padding: 5px 0;
width: 20%; /*** make the centering look more vivid ****/
background: #Cc3399;
color: #eee;
float: left;
text-align: center;
border-left: 1px solid #fff;
}
nav ul li a:hover {
background: #a2b3a1;
color: #000
}
您可以在jsfiddle
上查看