相对于中间一个div定位两个div元素。

4

我需要将元素#center-navigation相对于页面中心居中,然后将另外两个元素放置在它的左侧(#logo)和右侧(#contacts)。目前在我的实现中,#center-navigation没有居中于页面上。使用Flexbox布局能否实现此功能?

#row {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

#logo {
  height: 20px;
  width: 80px;
  background-color: red;
  margin-right: auto;
}

#contacts {
  margin-left: auto;
}

h1 {
  text-align: center;
}
<div id="row">
  <div id="logo">
  
  </div>
  <div id="center-navigation">
    Some navigation here
  </div>
  <div id="contacts">
    example@mail.org
  </div>
</div>
<h1>
  Some long website title goes here
</h1>


你能添加需求的截图吗? - Nitheesh
3个回答

1
你可以尝试使用CSS Grid:

#row {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  justify-content: space-between;
  align-items: center;
  text-align: center;
}

#logo {
  height: 20px;
  width: 80px;
  background-color: red;
}

#contacts {
  background-color: blue;
  text-align: right;
}

#center-navigation {
  background-color: green;
}

h1 {
  text-align: center;
  background-color: yellow;
}
<div id="row">
  <div id="logo">
  
  </div>
  <div id="center-navigation">
    Some navigation here
  </div>
  <div id="contacts">
    example@mail.org
  </div>
</div>
<h1>
  Some long website title goes here
</h1>


我之前尝试过。这里有一些导航相对于h1不居中。 - vlmdgbbgg
你试过使用网格吗?我改变了答案。 - Nikola Pavicevic

0

#contacts 的宽度应该与 #logo 的宽度相等。

#contacts, #logo{
  width: 20%
}


0

使用flexbox无法实现!
我建议您使用position:absolute

#row {
  /*display: flex;*/
  /*flex-direction: row;*/
  /*justify-content: center;*/
  /*align-items: center;*/
  text-align:center;
  position:relative;
}

#logo,#contacts{
  position:absolute;
  left:0;
  top:50%;
  transform:translateY(-50%);
}

#logo {
  height: 20px;
  width: 80px;
  background-color: red;
  margin-right: auto;
}

#contacts {
  margin-left: auto;
  left:auto;
  right:0;
}

h1 {
  text-align: center;
}
<div id="row">
  <div id="logo">
  
  </div>
  <div id="center-navigation">
    Some navigation here
  </div>
  <div id="contacts">
    example@mail.org
  </div>
</div>
<h1>
  Some long website title goes here
</h1>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接