我正在学习如何使用基本的 html 代码和页面布局。我有以下 html 和 css 代码。我希望导航栏在页面顶部居中对齐。如果我现在运行它,它看起来很接近我想要的,但它卡在了左边。
HTML:
<head>
<meta charset="utf-8" />
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="nav">
<ul>
<li><a>A</a></li>
<li><a>B</a>
<ul>
<li><a>BA</a></li>
<li><a>BB</a></li>
</ul>
</li>
<li><a>C</a>
<ul>
<li><a>CA</a></li>
<li><a>CB</a></li>
<li><a>CC</a></li>
<li><a>CD</a></li>
</ul>
</li>
<li><a>D<a></li>
</ul>
</div>
</body>
</html>
CSS:
body{
background: url('nature.jpg') no-repeat;
background-size: cover;
font-family: Arial;
color: white;
}
.nav ul{
padding: 0px;
list-style: none;
}
.nav ul li{
float: left;
width: 200px;
height: 40px;
background-color: black;
opacity: .8;
line-height: 40px;
text-align: center;
font-size: 20px;
margin-right: 2px;
}
.nav ul li a{
text-decoration: none;
color: white;
display: block;
}
.nav ul li a:hover{
background-color: green;
}
.nav ul li ul li{
display: none;
}
.nav ul li:hover ul li{
display: block;
}
我尝试根据各种文章更改显示和 float 值,但我没有找到任何有效的方法。谢谢你的帮助。
最佳答案
margin auto 是一个非常好的解决方案。在您的 css 文件中,只需将这两个属性添加到 .nav 类
.nav {
margin: 0 auto;
width: fit-content;
}
它会让你的 nav div 的宽度刚好适合内容,然后由于自动边距将它定位到中心。干杯
关于html - 中心 html/css 导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123724/