【问题标题】:How to center align/justify menu items in NavBar's media query?如何在 NavBar 的媒体查询中居中对齐/对齐菜单项?
【发布时间】:2018-10-03 13:07:14
【问题描述】:

我的第一个网站专注于 Apple 风格的简约风格。这是我从几个来源和这里的一个问题学习后开发的代码。我的最后一个问题是在移动视图中设置导航栏的样式(媒体查询处于活动状态)。现在我相信 flex-display(它解决了我的第一个问题)会导致所有菜单项在移动视图中保持水平扩展并单击栏图标。当菜单栏关闭时,目前它是完美的,徽标最终位于 NavBar 的中间。在这一点上,我唯一需要更改的是在“移动视图”中单击/展开条形图标时菜单项的格式,以及确保在激活菜单时导航栏的背景正确展开。

干杯

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;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.topnav a {
  display: inline-flex;
  color: #fff;
  text-align: justify;
  text-decoration: none;
  font-size: 15px;
  font-weight: lighter;
  transition: 0.3s;
  padding: 0;
  margin: 5px 60px 5px 60px;
  list-style-type: none;
}

.topnav a:hover {
  color: #4286f4;
}

.active {
  background-color: #333;
  color: #4286f4;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 800px) {
  .topnav a:not(:first-child) {
    display: none;
  }
  .topnav a.icon {
    float: left;
    display: flex;
    position: absolute;
    left: 0;
    top: 9px;
  }
}

@media screen and (max-width: 800px) {
  .topnav.responsive {
    position: static
  }
  .topnav.responsive .icon {
    position: absolute;
    left: 0;
    top: 9px;
  }
  .topnav.responsive a {
    float: left;
    display: inline;
    text-align: center;
    line-height: 100px;
  }
}
<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">
  <a href="#"><img src="Images/DivinitalLogo.png" width="30" height="30"></a>
  <a href="#home">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>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    将此 CSS 类代码添加到您的媒体查询。

    JsFiddle:https://jsfiddle.net/2sfjmz4n/

    CSS:

    @media screen and (max-width: 800px) {
        .topnav{
            flex-direction: column;
        }
    }
    

    这将使您的 .topnav 中的项目在移动视图上对齐/居中

    【讨论】:

    • 哇,这就像一个魅力。我想我只需要找到一个完全更新的 HTML/CSS 参考,因为我在浏览时从未见过 flex-direction。再次感谢。
    猜你喜欢
    • 2023-01-26
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多