使用justify-content时正确地使项目居中:中间的空格 [英] Center items correctly when using justify-content: space-between

查看:34
本文介绍了使用justify-content时正确地使项目居中:中间的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a header bar and want to place 3 items there. The first should be aligned on the left side, the second in the middle of the header and the third on the right side.

我为此而努力

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:空格; 时,这些项目无法正确居中.该图像比右侧的小按钮占据更大的位置.

but when using justify-content: space-between; the items don't get centered correctly. The image takes a bigger place than the small button on the right.

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

So the link in the middle is not centered correctly, it overlaps the right side. I want the link being in the horizontal center of the page.

推荐答案

您可以执行以下操作:

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>

这篇关于使用justify-content时正确地使项目居中:中间的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆