3个相同宽度的flexbox项目的水平居中

时间:2015-12-29 08:11:27

标签: html css html5 css3 flexbox

我一直试图使用flexbox水平居中这3个项目,但没有成功。它们都需要具有相同的宽度。 的 HTML:

 <div id="contact_flex_container">
    <div id="fb">
        <img src="img/contact/fb.png" class="contact_img">
        <h3>Title1</h3>
    </div>

    <div id="yt">
        <img src="img/contact/yt.png" class="contact_img">
        <h3>Title2</h3>
    </div>

    <div id="mail">
        <img src="img/contact/mail.png" class="contact_img">
        <h3>Title3</h3>
    </div>
</div>

CSS:

#contact_flex_container {
    display: flex;
    flex-flow: row wrap;
    text-align: center;
    background-color: red;
    width: auto;
    justify-content: space-around;
}

.contact_img {
    width: 40px;
    height: 40px;
}

#fb {
    flex-basis: 0;
    flex-grow: 1;
}

#yt {
    flex-basis: 0;
    flex-grow: 1;
}

#mail {
    flex-basis: 0;
    flex-grow: 1;
}

我还尝试为每个孩子设置左右边距自动设置,为容器设置居中内容,甚至将容器的固定宽度与像素组合,但似乎没有任何效果。更具体地说,无论我在那里放置什么价值,合理内容在这里似乎根本不起作用。我错过了什么或做错了什么?

1 个答案:

答案 0 :(得分:3)

您分配给flex-items的flex属性使它们尽可能大(在这种情况下为容器的33%)。

只需删除它们,然后将父级更改为justify-content:center

&#13;
&#13;
#contact_flex_container {
  display: flex;
  flex-flow: row wrap;
  text-align: center;
  background-color: red;
  width: auto;
  justify-content: center
}
.contact_img {
  width: 40px;
  height: 40px;
}
#fb {} #yt {} #mail {}
&#13;
<div id="contact_flex_container">
  <div id="fb">
    <img src="http://lorempixel.com/image_output/abstract-q-c-50-50-5.jpg" class="contact_img">
    <h3>Title1</h3>
  </div>

  <div id="yt">
    <img src="http://lorempixel.com/image_output/abstract-q-c-50-50-5.jpg" class="contact_img">
    <h3>Title2</h3>
  </div>

  <div id="mail">
    <img src="http://lorempixel.com/image_output/abstract-q-c-50-50-5.jpg" class="contact_img">
    <h3>Title3</h3>
  </div>
</div>
&#13;
&#13;
&#13;

备用,基于扩展的要求。

需要一个额外的包装器,它应该是inline-flex

&#13;
&#13;
#contact_flex_container {
  display: flex;
  flex-flow: row wrap;
  text-align: center;
  background-color: red;
  width: auto;
  justify-content: center
}
.wrap {
  display: inline-flex;
}
.wrap > div {
  flex: 1;
  border: 1px solid grey;
}
.contact_img {
  width: 40px;
  height: 40px;
}
&#13;
<div id="contact_flex_container">
  <div class="wrap">

    <div id="fb">
      <img src="http://lorempixel.com/image_output/abstract-q-c-50-50-5.jpg" class="contact_img">
      <h3>Lorem ipsum dolor sit.</h3>
    </div>

    <div id="yt">
      <img src="http://lorempixel.com/image_output/abstract-q-c-50-50-5.jpg" class="contact_img">
      <h3>Lorem ipsum.</h3>
    </div>

    <div id="mail">
      <img src="http://lorempixel.com/image_output/abstract-q-c-50-50-5.jpg" class="contact_img">
      <h3>Lorem</h3>
    </div>
  </div>
&#13;
&#13;
&#13;