gpt4 book ai didi

css - 如何使导航居中

转载 作者:行者123 更新时间:2023-11-28 05:40:06 25 4
gpt4 key购买 nike

我发现这种在 w3schools ( article ) 上制作响应式菜单的方法非常简单,但几天来我一直在努力尝试将其水平居中。

html

 <ul class="topnav">
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li class="icon">
<a href="javascript:void(0);" onclick="myFunction()">&#9776;</a>
</li>
</ul>

CSS

 /* Remove margins and padding from the list, and add a black background color */
ul.topnav {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}

/* Float the list items side by side */
ul.topnav li {float: left;}

/* Style the links inside the list items */
ul.topnav li a {
display: inline-block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
transition: 0.3s;
font-size: 17px;
}

/* Change background color of links on hover */
ul.topnav li a:hover {background-color: #111;}

/* Hide the list item that contains the link that should open and close the topnav on small screens */
ul.topnav li.icon {display: none;}

最佳答案

我用你的链接代码做了一个 fiddle :https://jsfiddle.net/gqm7zdf9/

一个可靠的选择是在您的 UL 周围添加一个包装器,以便您可以将背景颜色移动到那里。然后将其放置在包装器内。

HTML

<div class="nav-wrapper">
<ul class="topnav">
...
</ul>
</div>

额外的 CSS

div.nav-wrapper {
background-color: #333;
}
div.nav-wrapper ul.topnav {
display: inline-block;
position: relative;
left: 50%;
transform: translateX(-50%);
}


如果您能够(取决于您需要支持的浏览器)使用 display:flex,还有一个更简单的方法。您只需要添加一些 CSS:

ul.topnav {
/* ... */
display: flex;
justify-content: center;
}

https://jsfiddle.net/gqm7zdf9/1/


我认为您可以从那里继续您的媒体查询...

关于css - 如何使导航居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37940734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com