【问题标题】:Am I able to position a logo in the centre of a nav bar using flexbox?我可以使用 flexbox 将徽标放置在导航栏的中心吗?
【发布时间】:2018-07-25 09:07:44
【问题描述】:

我正在尝试使徽标居中,使其始终位于导航栏的中心,无论有多少导航链接。

如果两侧的项目都是偶数,这对我来说就很容易了,例如左侧的 2 个链接和右侧的 2 个链接,但我试图让左侧的 3 个和右侧的 2 个链接居中的徽标。

是否可以使用 flexbox 属性使图像居中,或者我必须以不同的方式进行处理,例如涉及绝对/相对定位?

header.main-header {
  background: url("../images/slides/slide-1.jpg") no-repeat 75%/cover;
  height: 100vh;
}

nav.nav-bar {
  background-color: tomato;
}

ul.container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0;
}

ul.container li {
  list-style-type: none;
}

li.logo img {
  max-width: 125px;
}
<header class="main-header">
  <nav class="nav-bar">
    <ul class="container">
      <li>My Story</li>
      <li>Wines</li>
      <li>How to Order</li>
      <li class="logo"><img src="http://placeimg.com/640/480/any" alt="Wines"></li>
      <li>Personal Sommelier</li>
      <li>Contact</li>
    </ul>
  </nav>
  <p style="text-align: center;">|<br>(Center)</p>
</header>

提前谢谢你。 祝你有美好的一天。 :)

【问题讨论】:

  • 总是3和2?
  • 正如我在您之前发布此内容时提到的那样..flexbox 无法使用您拥有的结构本地执行此操作 - stackoverflow.com/questions/38948102/…
  • 没有flexbox怎么办?仅仅通过使用绝对和相对定位以及一些媒体查询?我确实尝试过,但我一定在某个地方搞砸了,因为它并没有真正完成原始图像的外观。 bootstrap 会是最好的选择吗?

标签: html css header flexbox nav


【解决方案1】:

一个想法是使用徽标作为背景并居中,然后依靠一些边距来调整菜单元素:

header.main-header {
  height: 100vh;
}

nav.nav-bar {
  background-color: tomato;
}

ul.container {
  display: flex;
  align-items: center;
  padding: 0;
  background:url(http://placeimg.com/640/480/any) center/contain no-repeat;
  min-height:100px;
}

ul.container li {
  list-style-type: none;
  margin:0 2%;
}
ul.container li:nth-child(3) {
  margin-right:auto;
}
<header class="main-header">
  <nav class="nav-bar">
    <ul class="container">
      <li>My Story</li>
      <li>Wines</li>
      <li>How to Order</li>
      <li>Personal Sommelier</li>
      <li>Contact</li>
    </ul>
  </nav>
  <p style="text-align: center;">|<br>(Center)</p>
</header>

但如果您可以调整 HTML,您可以简单地将菜单分成两部分:

header.main-header {
  height: 100vh;
}

nav.nav-bar {
  background-color: tomato;
  display:flex;
  align-items:center;
}

ul.container {
  display: flex;
  align-items: center;
  justify-content:space-around;
  flex:1;
  padding: 0;
}
img {
  max-width:100px;
}
ul.container li {
  list-style-type: none;
  margin:0 2%;
}
<header class="main-header">
  <nav class="nav-bar">
    <ul class="container">
      <li>My Story</li>
      <li>Wines</li>
      <li>How to Order</li>
    </ul>
     <img src="http://placeimg.com/640/480/any" >
    <ul class="container">
      <li>Personal Sommelier</li>
      <li>Contact</li>
    </ul>
  </nav>
  <p style="text-align: center;">|<br>(Center)</p>
</header>

【讨论】:

  • 我喜欢这种想法,我从来没有这样想过,但是是的 :-D
  • @KarlC 我添加了另一种方式 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 2013-05-05
  • 1970-01-01
相关资源
最近更新 更多