灵活的图像和文本响应列,无需媒体查询

时间:2019-07-07 20:47:10

标签: html css flexbox

我有一个flex难题:我想做的就是将flex用于响应列,其中,当视口变窄时,右侧列将在行下方移动,而无需使用媒体查询。这适用于图像;但我无法使文字进入图像下方-即使在图像下方以自己的<div>,它也浮动在右侧。我究竟做错了什么?是否有更好的方法来进行媒体查询?

https://jsfiddle.net/9n8pdbq5/

HTML

<div class="issues-columns">

<div class="issue-col">
<img src="https://placekitten.com/200/200"/>
Text text text
</div>

<div class="issue-col">
<img src="https://placekitten.com/200/200"/>
Text text text
</div>

<div class="issue-col">
<img src="https://placekitten.com/200/200"/>
Text text text
</div>
</div>

CSS

.issues-columns {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
}

.issue-col {
flex-grow: 1;
flex-shrink: 0;
flex-basis: 33.3333%;
flex-basis: 300px;
display: flex;
align-items: center;
justify-content: center;
}

2 个答案:

答案 0 :(得分:2)

在父元素上将flex-direction设置为column。然后将两个孩子imgtext都设置为display: inline-flex

.issues-columns {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.issue-col {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3333%;
  flex-basis: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

span {
  display: inline-flex;
}
<div class="issues-columns">

  <div class="issue-col">
    <img src="https://placekitten.com/200/200"/>
    <span>Text text text</span>
  </div>

  <div class="issue-col">
    <img src="https://placekitten.com/200/200"/>

    <span>Text text text</span>
  </div>

  <div class="issue-col">
    <img src="https://placekitten.com/200/200"/>

    <span>Text text text</span>
  </div>
</div>

谈到您的“做错了事”,HTML会从左至右读取div元素中的所有内容(就像读取任何文本内容一样)。要淡化您的文字,您应该明确告诉textimage都是两个具有各自权利的子元素,父元素应分别对待。

答案 1 :(得分:1)

解决方案是将图像和文本包装成另外div 现在,您将获得输出为 DIV 1 现在,文字将紧随图像之后,这是因为<img />inline-element

其他两个div's的文字下面有文字,因为我将文字包装在<h2>中。文字在图片下方,因为<h2>block-element

了解更多Inline Vs Block Elements

.issues-columns {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.issue-col {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3333%;
  flex-basis: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="issues-columns">
 <!-- DIV 1 -->
  <div class="issue-col">
    <div>
      <img src="https://placekitten.com/200/200" /> Text text text
    </div>
  </div>

  <div class="issue-col">
    <div>
      <img src="https://placekitten.com/200/200" />
      <h2>Text text text </h2>
    </div>
  </div>

  <div class="issue-col">
    <div>
      <img src="https://placekitten.com/200/200" />
      <h2>Text text text </h2>
    </div>
  </div>