在柔性显示器中将图像水平居中?

时间:2019-04-12 19:19:29

标签: css css3 flexbox centering

我不会在flex导航栏中居中放置图像,但我不能,我已经尝试过这样做:How to center an image within a flex item (cell),但是不起作用。

nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-radius: 1.5em;
}

nav #this img {
  height: 5em;
  width: 5em;
}

.item {
  width: 45%;
  display: flex;
  justify-content: space-around;
  line-height: 3.2em;
  font-size: 1.75em;
}

.login {
  width: 20%;
  display: flex;
  justify-content: space-around;
  align-self: center;
}
<nav>
  <div class="item">
    <div> Content </div>
    <div> Content </div>
  </div>
  <div id="myimage">
    <img src="https://via.placeholder.com/150x50">
  </div>
  <div class="login">
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
  </div>
</nav>

3 个答案:

答案 0 :(得分:0)

我不知道你到底在做什么?

nav #this img {
 height: 5em;
 width: 5em;
}

我认为您想要这样的东西:

nav #myimage img {
 height: 5em;
 width: 5em;
}

要在flexbox中居中,请在flexbox父元素中将justify-content用作主轴,并将align-items对准辅助轴。 在这种情况下,您可以在导航中进行操作,并将3个直接子div对齐到中心。

nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-radius: 1.5em;
  align-items: center;
}

相反,如果您想将图像放置在其父div中,则将其设置为display:flex并将项目与父元素(#myimage)对齐:

#myimage{
 display:flex;
 align-items:center;
}

答案 1 :(得分:0)

我只是用很少的更新来更新您的CSS。试试这个,希望对您有所帮助。谢谢

nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-radius: 1.5em;
}

nav #this img {
  height: 5em;
  width: 5em;
}

.item {
  width: 45%;
  display: flex;
  justify-content: space-around;
  font-size: 1.75em;
}

.login {
  width: 20%;
  display: flex;
  justify-content: space-around;
  align-self: center;
}

.flexItem {
  flex: 1;
  flex-wrap: wrap;
  align-items: center;
}
<nav>
  <div class="item flexItem">
    <div> Content </div>
    <div> Content </div>
  </div>
  <div id="myimage">
    <img src="https://via.placeholder.com/150x50">
  </div>
  <div class="login flexItem">
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
  </div>
</nav>

答案 2 :(得分:0)

nav {
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-radius: 1.5em;
}

nav #this img {
  height: 5em;
  width: 5em;
}

.item {
  width: 45%;
  display: flex;
  justify-content: space-around;
  line-height: 3.2em;
  font-size: 1.75em;
}

.login {
  width: 20%;
  display: flex;
  justify-content: space-around;
  align-self: center;
}
#myimage {
    display: flex;
    justify-content: center;
    align-items: center;
}
<nav>
  <div class="item">
    <div> Content </div>
    <div> Content </div>
  </div>
  <div id="myimage">
    <img src="https://via.placeholder.com/150x50">
  </div>
  <div class="login">
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
    <div> Content </div>
  </div>
</nav>