使用justify-content:space-between时正确居中项目

时间:2017-12-14 10:54:32

标签: html css

我创建了一个标题栏,并希望在那里放置3个项目。第一个应该在左侧对齐,第二个在标题的中间对齐,第三个在右侧。

我去了这个

body{
  background: #eeeeee;
}

#header {
  background: #ffffff;
  height: 53px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.headerEle {
  
}
<div id="header">
  <img class="headerEle" src="https://cdn.discordapp.com/attachments/316916526760591362/390814093340311565/unknown.png">

  <a class="headerEle" href="https://www.google.de/">Google</a>

  <button class="headerEle">Logout</button>
</div>

但使用justify-content: space-between;时,项目无法正确居中。图像比右边的小按钮占用更大的位置。

因此中间的链接没有正确居中,它与右侧重叠。我希望链接位于页面的水平中心。

3 个答案:

答案 0 :(得分:2)

您可以这样做:

body {
  background: #eee;
}

#header {
  background: #fff;
  height: 53px;
  display: flex;
  /*flex-direction: row; not necessary, by default*/
  align-items: center;
  justify-content: space-between;
}

#header > span {flex: 1} /* each 33.33% of the parent's width */

img {display: block; max-width: 100%; max-height: 100vh} /* responsiveness; "display: block" removes bottom margin/whitespace */

.link {
  display: flex;
  justify-content: center; /* horizontally centered */
}

.btn {
  display: flex;
  justify-content: flex-end; /* placed far right */
}
<div id="header">
  <span>
    <img class="headerEle" src="https://cdn.discordapp.com/attachments/316916526760591362/390814093340311565/unknown.png">
  </span>
  <span class="link">
    <a class="headerEle" href="https://www.google.de/">Google</a>
  </span>
  <span class="btn">
    <button class="headerEle">Logout</button>
  </span>
</div>

答案 1 :(得分:1)

您可以使用<a>元素的绝对定位来精确居中标题上的链接:

body{
  background: #eeeeee;
}
#header {
  background: #ffffff;
  height: 53px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  position:relative;
}
#header a {
  position:absolute;
  left:50%;
  top:50%;
  transform:translate(-50%, -50%);
}
<div id="header">
  <img class="headerEle" src="https://cdn.discordapp.com/attachments/316916526760591362/390814093340311565/unknown.png">
  <a class="headerEle" href="https://www.google.de/">Google</a>
  <button class="headerEle">Logout</button>
</div>

答案 2 :(得分:1)

这是你想要做的吗?

body{
  background: #eeeeee;
}

#header {
  background: #ffffff;
  height: 53px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
#header > div {
    -webkit-flex: 1; /* Safari 6.1+ */
    -ms-flex: 1; /* IE 10 */
    flex: 1;
    text-align: center;
}
<div id="header">
    <div>
        <img class="headerEle" src="https://cdn.discordapp.com/attachments/316916526760591362/390814093340311565/unknown.png">
    </div>
    <div>
        <a class="headerEle" href="https://www.google.de/">Google</a>
    </div>
    <div>
        <button class="headerEle">Logout</button>
    </div>
</div>