我有一个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;
}
答案 0 :(得分:2)
在父元素上将flex-direction
设置为column
。然后将两个孩子img
和text
都设置为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
元素中的所有内容(就像读取任何文本内容一样)。要淡化您的文字,您应该明确告诉text
和image
都是两个具有各自权利的子元素,父元素应分别对待。
答案 1 :(得分:1)
解决方案是将图像和文本包装成另外div
现在,您将获得输出为 DIV 1
现在,文字将紧随图像之后,这是因为<img />
是inline-element
其他两个div's
的文字下面有文字,因为我将文字包装在<h2>
中。文字在图片下方,因为<h2>
是block-element
。
.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>