(注意:这里有一些关于我如何获得此效果的背景故事;如果您不在乎,请随时跳过大胆的文字。 )
回到过去的黑暗时代,如果您想拥有一个带有可变宽度的图像,旁边的一些文本,您只需使用一个表即可完成:
<table>
<tr>
<!-- This TD will magically grow to fit its image -->
<td><img src="someImage.png"/></td>
<!-- This TD will magically grow to fill the remaining space -->
<td>Lorem ipsum ...</td>
</tr>
</table>
但是,在现代网络设计中,我们应该使用CSS而不是表格,我知道如何通过在图像和文本上使用 float:左
获得类似的效果。
但是, float
现在也是Passe,每个人都使用(包装)flexbox进行布局。但是,当我这样做时:
<div style="display: flexbox; flex-wrap: wrap;">
<div><img src="someImage.png"/></div>
<div>Lorem ipsum ...</div>
</div>
我的文本div出现在我的图像div下方。我可以通过将显式 max Width
样式放在两个上来解决此问题,但是我的文本&lt; div&gt;
不再填充图像留下的空间(例如,如果我有一个较小的图像,我用一堆白色的空格结束。
我的问题是:如何与一些文本并排创建图像的弹性箱...但是要有flexbox的两个“列”调整自己,以便图像列与图像一样宽,文本列与“任何剩下的空间”一样宽??
(NOTE: There's a bit of backstory here about how I used to get this effect; feel free to skip to the bold text at the end if you don't care.)
Back in the dark old days, if you wanted to have an image with a variable width, and some text next to it, you would just do it with a table:
<table>
<tr>
<!-- This TD will magically grow to fit its image -->
<td><img src="someImage.png"/></td>
<!-- This TD will magically grow to fill the remaining space -->
<td>Lorem ipsum ...</td>
</tr>
</table>
However, in modern web design we should be using CSS not tables, and I know how to get a similar effect by using float: left
on both the image and the text.
But, float
is passe now too, and everyone uses (wrapping) flexboxes for layouts. However, when I do:
<div style="display: flexbox; flex-wrap: wrap;">
<div><img src="someImage.png"/></div>
<div>Lorem ipsum ...</div>
</div>
My text div appears below my image div. I can fix this by putting explicit max-width
styles on both, but then my text <div>
no longer fills the space left by the image (eg. if I have a smaller image, I wind up with a bunch of whitespace).
My question is: how can I create a flexbox of an image side-by-side with some text ... but have the two "columns" of the flexbox adjust themselves so that the image column is as wide as the image, and the text column is as wide as "whatever space is left"?
发布评论
评论(2)
为了实现此目的,您只需要使用
flex-wrap:nowrap
它将将flex项目迫使flex项目分成一条线,从而为图像提供全宽度,并将其休息至文本。以下是两个代码
1。
2.包裹
In order to achieve this you just need to use
flex-wrap:nowrap
it will force the flex items into a single line giving full width to the image and rest to the text.Below are two codes
1. with nowrap
2.with wrap
如果您不希望文本列与大图像旁边没有足够的空间,则可以将其包裹在新行中,您可以简单地从容器中删除
Flex-wrap
。这是您要寻找的行为吗?
阅读 css-tricks' >将帮助您迅速发展。
If you don't want your text column to wrap around into a new row if there's not enough space for it alongside a large image, you can simply remove the
flex-wrap
from your container.Is this the kind of behaviour you're looking for?
Reading through the MDN basic concepts of flexbox and perhaps also CSS-tricks' 'A complete guide to Flexbox' will help get you up to speed.