简体   繁体   English

如何在响应式菜单中居中对齐导航链接?

[英]How to center-align the navigation links in responsive menu?

The menu below is left-aligned.下面的菜单是左对齐的。 How can we make the links center-aligned (horizontally).我们如何使链接居中(水平)。

 function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } }
 body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: #333; } .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .active { background-color: #4CAF50; color: white; } .topnav .icon { display: none; } @media screen and (max-width: 600px) { .topnav a:not(:first-child) { display: none; } .topnav a.icon { float: right; display: block; } } @media screen and (max-width: 600px) { .topnav.responsive { position: relative; } .topnav.responsive .icon { position: absolute; right: 0; top: 0; } .topnav.responsive a { float: none; display: block; text-align: left; } }
 <body> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div> <div style="padding-left:16px"> <h2>Responsive Topnav Example</h2> <p>Resize the browser window to see how it works.</p> </div> </body>

Generally speaking, it would be more practical for you to use flex to position such items, rather than wrestling with floats.一般来说,使用 flex 来定位这些项目会更实用,而不是与浮动搏斗。

To get you started, on .topnav , apply:为了让你开始,在.topnav ,申请:

display: flex;
justify-content: center;

On .topnav a , you could remove float: left ..topnav a ,您可以删除float: left There's other floats you could replace with flex (for more control) as well, but it's up to you if they're useful as-is, and what techniques you want to use.您还可以用 flex 替换其他浮点数(以获得更多控制),但是它们是否按原样有用以及您想使用什么技术取决于您。 In any case, it seems you probably have to make changes to your @media code as well.无论如何,您似乎还必须对@media 代码进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM