【问题标题】:How to align some elements of a navigation bar in CSS?如何在 CSS 中对齐导航栏的某些元素?
【发布时间】:2021-10-14 09:34:42
【问题描述】:

我正在使用 HTML 和 CSS 制作导航栏。我有 3 个元素:2 个 a-href 和 1 个按钮

HTML:

  <nav>
    <ul>
      <li>
        <a href="/signin">Home</a>
      </li>
      <li>
        <a href="/games">Games</a>
      </li>
      <button class="btn-item btn-ghost red secundary round">
        Sign Out
      </button>
    </ul>
    <div class="hide"><i class="fa fa-bars" aria-hidden="true"></i> Menu</div>
  </nav>

我有这些风格:

CSS:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: monospace;
  font-size: 20px;
}

nav ul {
  list-style: none;
  background: black;
  text-align: left;
}


nav ul li {
  display: inline-block;
  padding: 20px;
  transition: all ease-in-out 250ms;
}

ul li a {
  color: white;
  text-decoration: none;
}

nav ul li:hover {
  background: red;
}

特别是这个块:

nav ul {
  list-style: none;
  background: black;
  text-align: left;
}

在text-align:left属性中,它负责对齐导航栏的所有元素,问题是我希望a href居中对齐,按钮右对齐。我怎样才能做到这一点?

【问题讨论】:

  • 你可以试试display: flex; justify-content: space-between;
  • 有很多选项,包括 flex。像 float:right 这样的老派方法,或者你可以绝对定位。如果你将你的 li 项目包装在一个容器中,Flexbox 就可以工作。

标签: javascript html css angular


【解决方案1】:
Try this:

`nav ul {
          list-style: none;
          background: black;
          text-align: center;
        }`

几乎只是将文本对齐更改为居中而不是左对齐,这就是结果。

【讨论】:

  • 好的,现在我怎样才能将 Home 和 Games 留在中间,然后将按钮向右对齐?
【解决方案2】:

抱歉回复晚了,补充一下

button{
  float: right;
  margin-top:15px;
} 

我正在使用代码笔,因此您可能需要调整页边距以适应您拥有的任何视图。如果您有任何其他问题,请告诉我。

【讨论】:

    【解决方案3】:

    试试这个。将 nav 标签改为主容器,而不是 ul,并做了一些其他的事情。

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: monospace;
      font-size: 20px;
    }
    
    nav {
      background: black;
      width: 100vw;
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    nav ul {
      list-style: none;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90%;
    }
    
    nav ul li {
      display: inline-block;
      padding: 20px;
      transition: all ease-in-out 250ms;
    }
    
    ul li a {
      color: white;
      text-decoration: none;
    }
    
    nav ul li:hover {
      background: red;
    }
      <nav>
        <ul>
          <li>
            <a href="/signin">Home</a>
          </li>
          <li>
            <a href="/games">Games</a>
          </li>
        </ul>
        <button id="myButton" class="btn-item btn-ghost red secundary round">
          Sign Out
        </button>
        <!-- <div class="hide"><i class="fa fa-bars" aria-hidden="true"></i> Menu</div> -->
      </nav>

    【讨论】:

      猜你喜欢
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多