我正在尝试建立一个div,其中包含一个浮动到左上角的图像和一个长度未知的文本。目标是如果文本比图像小,则使文本居中于div的中间;如果文本够多,则将其环绕在图像中。
我的总体布局是:
<div class="wrapper">
<img src="http://placekitten.com/50/50" class="image" style="float: left">
<p class="text">
Text goes here
</p>
</div>
我尝试过显示表和flexbox,但是它们将图像和文本视为不同的块,并防止长文本环绕图像。固定高度也不起作用,因为文本的长度是可变的,并且在开始环绕图像之前,可能需要垂直对齐几行。
我已经设置了一个fiddle并尝试获取结果。它使用两种不同的硬编码样式,但是我试图找到一个无论提供多少文本都可以使用的解决方案。
是否可以通过某种方式来解决此问题,而无需某种JavaScript攻击?
答案 0 :(得分:1)
一个解决方案是使用包装器包装内容,以使它不继承flex属性作为直接后代。这也使您可以根据需要使用flex来获得一些灵活性。
.wrapper {
border: 1px solid black;
padding: 0;
overflow: auto;
display: flex;
}
.image {
vertical-align: middle;
}
.text {
margin: 0;
}
.content {
flex: 1;
}
.content p {
display: inline;
vertical-align: middle;
}
<p>
This text should be centered vertically:
</p>
<div class="wrapper">
<div class="content">
<img src="http://placekitten.com/50/50" class="image">
<p class="text">
A little bit of text!
</p>
</div>
</div>
<p>
This text should wrap around the image, going underneath it:
</p>
<div class="wrapper">
<div class="content">
<img src="http://placekitten.com/50/50" class="image">
<p class="text">
A lot of text! I mean a whole lot! Like tons and tons! You won't believe how much text. It's still going even. How is it still going? Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going?
Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going? Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going? Who
knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going? Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! Oh wait, it's over.
</p>
</div>
</div>
<p>
This is what I'm trying to avoid:
</p>
<div class="wrapper">
<div class="content">
<img src="http://placekitten.com/50/50" class="image">
<p class="text">
A lot of text! I mean a whole lot! Like tons and tons! You won't believe how much text. It's still going even. How is it still going? Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going?
Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going? Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going? Who
knows, but it's doing it! Oh wow it just isn't stopping. So much text! It's still going even. How is it still going? Who knows, but it's doing it! Oh wow it just isn't stopping. So much text! Oh wait, it's over.
</p>
</div>
</div>