【问题标题】:Center responsive navigation bar中心响应式导航栏
【发布时间】:2020-03-05 05:38:34
【问题描述】:

我正在按照 w3schools 的指南为我的网站构建响应式顶部导航栏:How TO - Responsive Top Navigation

但是,我希望导航项在页面上居中,而不是左对齐或右对齐。 w3schools 甚至还有关于中心导航元素 link 的第二个教程,但是当我尝试将此代码用于多个导航元素时,它们要么都在彼此内部,要么彼此堆叠!

更令我沮丧的是,之前有一个关于这个确切问题的问题(here),但似乎同时示例的代码已经更改了很多,因此答案不再适用。 :(

【问题讨论】:

    标签: html css css-float


    【解决方案1】:

    要使您提供的链接中的顶部导航居中,您可以将以下内容添加到.topnav

    .topnav {
      …
      display: flex;
      justify-content: center;
    }
    

    要处理移动菜单(而不是居中),请将以下内容添加到您的 @media 查询中:

    @media screen and (max-width: 600px) {
      …
      .topnav { display: block; }
    }
    

    之前

    之后

    【讨论】:

    • 这在桌面视图中工作得很好,但在小屏幕上会弄乱行为。可能我需要在 @media 屏幕和 css 的 (max-width: 600px) 部分添加一些东西?
    • @terri 对。您可以调整媒体查询中的内容。我不确定你打算用移动菜单做什么。
    【解决方案2】:

    一种方法是将链接包装在一个 div 中(例如,一个类为 nav-links 的 div),然后应用到该 div:

    .nav-links {
        width: fit-content; /* 'margin: auto' alone does not work if the div takes full width */
        margin: auto;
    }
    

    以下是基于您链接的教程的演示:

    .nav-links {
      width: fit-content;
      margin:auto;
    }
    
    /*//////////////  W3Schools CSS code //////////////*/
    
    /* Add a black background color to the top navigation */
    .topnav {
      background-color: #333;
      overflow: hidden;
    }
    
    /* Style the links inside the navigation bar */
    .topnav a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    
    /* Change the color of links on hover */
    .topnav a:hover {
      background-color: #ddd;
      color: black;
    }
    
    /* Add an active class to highlight the current page */
    .topnav a.active {
      background-color: #4CAF50;
      color: white;
    }
    
    /* Hide the link that should open and close the topnav on small screens */
    .topnav .icon {
      display: none;
    }
    <!-- Load an icon library to show a hamburger menu (bars) on small screens -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    
    <div class="topnav" id="myTopnav">
      <div class="nav-links">
        <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>

    【讨论】:

    • 我尝试了您的解决方案,但无论是在 sn-p 还是在我自己的代码中,它都没有真正居中。我接受了另一种解决方案,因为它按我的意图工作。
    • @terri Weird,sn-p 在我的浏览器(Chrome - Windows)上运行良好。你在什么浏览器上尝试这个?
    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    相关资源
    最近更新 更多