使导航栏居中

Making a navigation bar centred

我正在尝试使我的导航栏看起来与该网站上的导航栏相似。 (http://thestyleinsider.weebly.com/) 我有两个与此相关的问题。即使我在 css 中使用了 "text-align: centre-right;",我也无法将链接居中(向右)。我还想知道如何将链接放到导航栏的中间(这样它们就不会粘在网页的顶部)。我试过调整 padding 但没有任何效果。非常感谢任何帮助!

http://codepen.io/anon/pen/PPxdyN

一个可能的答案是这样的。将文本设置为右对齐,行高足以到达导航栏的中间。

nav {
  line-height:80px;
  text-align: right;
}

据我所知,文本对齐不适用于多个属性。这是我会做的。

1) 降低主导航的高度 class。

3) 设置text-align:right,并给它一些填充。这个填充给主导航它的高度并使链接垂直居中。

.main {position: relative;}
    .main-nav {
      background-color: black;
      z-index: 150;
      text-align:right;
      padding:20px;
      position: fixed;
      width: 100%;
      top:0;}
    .main-nav-scrolled {
      position: fixed;
      width: 100%;
      top: 0;
      background: yellow;}
    a:link, a:visited {
      width: 100%;
      text-align: center-left;
      padding: 8px;
      text-decoration: none;
      text-transform: uppercase;
      height: 80px;
      border-bottom: 18px;
      border-top: 18px;}
a {
  color: white;
  text-decoration: none;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
a:hover {
  background-color: #ffbc00;
}
a img {
  border: 0;
}
ol,
ul {
  list-style-type: none;
}
<nav class="main-nav">
  <a href="index3.html">Home</a>
  <a</a>
  <a href="contact.html">Contact</a>
  <a href="directory.html">Directory</a>
</nav>

为什么要尝试对齐文本?这正是 flexbox 的发明目的。

nav {
    display: flex;
}

nav a:first-child {
    margin-left: auto;
}

看看这个 working codepen example

将 display:flex 应用到导航容器会改变其 children 的行为并将它们变成弹性项目。这又是changes the behaviour of margin-left。现在将第一个导航 child 的 margin-left 设置为自动可确保弹性项目左侧的整个 space 被填充并将它们全部移动到右侧。

更新

我已经更新了我的答案,以同时考虑到您希望在左侧显示。通过使用 flexbox,您可以将徽标作为最后一个 child 添加到导航容器,仍然可以使用 :first-child。通过更改最后一个 child(其中包含徽标并具有 .logo class)的顺序,您可以将其切换到第一个位置。然而,这并没有使它成为 :first-child,因此没有得到 margin-left 应用。

nav {
    display: flex;
}

nav a {
    order: 2;
}

nav a.logo {
    order: 1;
}

nav a:first-child {
    margin-left: auto;
}

看看这个 updated codepen example

更新 2

作为 Henri Vonfire ,您也可以将徽标用作 first-child 并使用 margin-right 让 flex 填充第一个和第二个 flex 之间的 space物品。这使得完全放弃订单更改成为可能。

nav {
    display: flex;
}

nav a:first-child {
    margin-right: auto;
}

看看这个 last codepen example