使用flexbox中的图像居中显示文字

时间:2016-10-18 18:50:52

标签: html css css3 flexbox center

我制作了一个网页,需要将3个div作为促销内容进行居中对齐,例如:

enter image description here

为了获得这种间距和对齐方式,我添加了不可见的图像,然后将其隐藏在移动设备上,以便它们得到响应,如下所示:

<div id="promocontent">
  <img class="img-responsive" src="img/iconenope.png">
  <img class="img-responsive hidden hide-on-med-and-down" src="img/iconehidden.png">
  <img class="img-responsive" src="img/iconenope.png">
  <img class="img-responsive hidden hide-on-med-and-down" src="img/iconehidden.png">
  <img class="img-responsive" src="img/iconenope.png"><br><br>
</div>

CSS:

#promocontent {
display: flex;                  /* establish flex container */
flex-direction: row;            /* default value; can be omitted */
flex-wrap: nowrap;              /* default value; can be omitted */
justify-content: space-between; /* switched from default (flex-start, see below) */
padding: 5px;
}

现在,我需要在这些图像的中下部添加文字,例如:

enter image description here

那么,我该怎么做(响应工作)?对齐2行文本(可能是1,但2会更好)。

谢谢。

2 个答案:

答案 0 :(得分:1)

#promocontent {
  display: flex;
  justify-content: space-between;
  padding: 5px;
}
#promocontent > div {
  display: flex;
  flex-direction: column;
  align-items: center;       /* horizontally center child elements */
  text-align: center;        /* horizontally center text on narrow screens;
                                see http://stackoverflow.com/q/39678610/3597276 */
}
<div id="promocontent">
  <div>
    <img class="img-responsive" src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt="">
    <h2>header text</h2>
    <span>text text text text text</span>
  </div>
  <div>
    <img class="img-responsive" src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt="">
    <h2>header text</h2>
    <span>text text text text text</span>
  </div>
  <div>
    <img class="img-responsive" src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt="">
    <h2>header text</h2>
    <span>text text text text text</span>
  </div>
</div>

https://jsfiddle.net/x2rzj1cu/2/

答案 1 :(得分:0)

我会避免使用额外的图像进行间距,只需依靠justify-content: space-between

随意查看我的codepen(与Michaels基本相同)。

http://codepen.io/anon/pen/zKmaVJ