html - 中心 html/css 导航栏

标签 html css nav

我正在学习如何使用基本的 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/

相关文章:

javascript - 如何使用 Javascript/jQuery 从 div 内容中去除 HTML 标签?

javascript - 是否有机会通过 css 将 div 类插入 javascript

css - Firefox 中的 Nivo slider 定位

html - 在垂直导航栏 ​​bootstrap 底部添加固定导航项

css - <nav> 和 <section> 元素不显示

html - Bootstrap 很慢如何让它更快

html - 在 Internet Explorer 中查看时更改站点

html - 如何制作 Bootstrap Navbar "non-responsive"?

html - 绝对 URL 不适用于完全静态的网站

css - 列表(导航)元素不会延伸到向右浮动的 div