中心 html/css 导航栏
Center html/css nav bar
我正在学习如何使用基本 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;
}
我尝试根据各种文章更改显示和浮动值,但我没有找到任何有效的方法。谢谢你的帮助。
margin auto 是一个非常棒的解决方案。在您的 css 文件中,只需将这两个属性添加到 .nav class
.nav {
margin: 0 auto;
width: fit-content;
}
它将使您的导航宽度 div 刚好适合内容,然后由于该自动边距将其定位到中心。干杯
改为
.nav ul li{ float: left; }
使用
.nav ul li{ display: inline-block; }
并添加
.nav{ text-align: center; }
我正在学习如何使用基本 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;
}
我尝试根据各种文章更改显示和浮动值,但我没有找到任何有效的方法。谢谢你的帮助。
margin auto 是一个非常棒的解决方案。在您的 css 文件中,只需将这两个属性添加到 .nav class
.nav {
margin: 0 auto;
width: fit-content;
}
它将使您的导航宽度 div 刚好适合内容,然后由于该自动边距将其定位到中心。干杯
改为
.nav ul li{ float: left; }
使用
.nav ul li{ display: inline-block; }
并添加
.nav{ text-align: center; }