首页 > 解决方案 > 如何垂直对齐动态长度的文本,同时让它环绕浮动图像?

问题描述

我正在尝试设置一个 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>

我尝试过显示表格和弹性框,但它们将图像和文本视为不同的块,并防止长文本环绕图像。固定高度也不起作用,因为文本的长度是可变的,并且在开始环绕图像之前可能需要垂直对齐几行。

我已经为我想要得到的结果设置了一个小提琴。它使用两种不同的硬编码样式,但我试图找到一个无论提供多少文本都可以工作的单一解决方案。

没有某种javascript hack有没有办法解决这个问题?

标签: htmlcssvertical-alignment

解决方案


解决这个问题的方法是用包装器包装内容,这样它就不会继承 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>


推荐阅读