首页 > 解决方案 > 如何居中导航栏和右侧的一项

问题描述

我想要一个中心导航栏,右边有一个这样的元素:我想要的例子

其实我做了这个:

* {
  margin: 0;
  padding: 0;
}

header {
  position: fixed;
  height: 35px;
  width: 100vw;
  z-index: 2;
  background-color: rgba(0, 0, 0, 1);
}

.nav {
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  height: 100%;
  align-items: center;
  text-transform: uppercase;
}

li {
  list-style: none;
}

.center {
  text-align: center;
  display: flex;
}

.right {
  right: 0;
  text-align: right;
}

.nav .text1 {
  color: #f2f2f2;
  padding: 15px 35px;
  text-decoration: none;
  font-size: 12px;
}
<header>
  <div class="nav">
    <div class="center">
      <li><a class="text1" href="#">one</a></li>
      <li><a class="text1" href="#">two</a></li>
      <li><a class="text1" href="#">tree</a></li>
    </div>
    <div class="right">
      <li><a class="text1" href="#">four</a></li>
    </div>
  </div>
</header>

我怎样才能把“四”元素放在正确的位置?

标签: htmlcss

解决方案


您非常接近,但忘记将.right元素的位置设置为绝对位置。right: 0不会对具有默认(又名静态)定位的元素做任何事情。https://developer.mozilla.org/en-US/docs/Web/CSS/position

* {
  margin: 0;
  padding: 0;
}

header {
  position: fixed;
  height: 35px;
  width: 100vw;
  z-index: 2;
  background-color: rgba(0, 0, 0, 1);
}

.nav {
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  height: 100%;
  align-items: center;
  text-transform: uppercase;
}

li {
  list-style: none;
}

.center {
  text-align: center;
  display: flex;
}

.right {
  position: absolute;
  right: 0;
  text-align: right;
}

.nav .text1 {
  color: #f2f2f2;
  padding: 15px 35px;
  text-decoration: none;
  font-size: 12px;
}
<header>
  <div class="nav">
    <div class="center">
      <li><a class="text1" href="#">one</a></li>
      <li><a class="text1" href="#">two</a></li>
      <li><a class="text1" href="#">tree</a></li>
    </div>
    <div class="right">
      <li><a class="text1" href="#">four</a></li>
    </div>
  </div>
</header>


推荐阅读