如何垂直对齐动态长度的文本,同时让它环绕浮动图像?

问题描述 投票:1回答:1

我正在尝试设置一个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 hack,有没有办法解决这个问题?

html css vertical-alignment
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.