html - 垂直对齐包装器 div 不适用于多行文本

标签 html css

我无法垂直对齐(居中)带有 2 行文本的 div。一行,是的,但不是 2。我希望其中一行像 h2,另一行像一个段落。我意识到我可以通过样式实现“h2”和“p”外观,但我不能将它们放在不同的行上。

https://jsfiddle.net/aaunr9wr/4/

<div class="wrapper">
    <div class="image-wrapper">
        <img src="http://lorempixel.com/output/food-q-g-300-200-9.jpg">
    </div>
    <div class="text-wrapper">
        <h2>Middle</h2>
        <p>How is this aligned?</p>
    </div>
</div>

.wrapper{
  border:1px solid #f00;
  width:90%;
  margin:0 auto;
  padding:1em;
}
.image-wrapper{
  display:inline;
  margin-right:1em;
  vertical-align:middle;
}
.text-wrapper{
  vertical-align:middle;
  display:inline;
}
.text-wrapper p{
  display:inline;
}
.text-wrapper h2{
  display:inline;
}
img{
 vertical-align:middle;
}
h2,p{
  margin:0;
}

我该怎么做?

最佳答案

ph2中移除inline,然后为设置display:inline-block .text-wrapper: https://jsfiddle.net/ilpo/aaunr9wr/5/

编辑:它不适用于多行的原因是它的最大宽度默认为 100%。因此,当您插入更多文本时,.text-wrapper 不再适合与图像位于同一文本行。您可以通过设置 max-width 来解决这个问题。您的 max-width 最多应该是 image 所占空间的剩余部分:

https://jsfiddle.net/ilpo/aaunr9wr/7/

关于html - 垂直对齐包装器 div 不适用于多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126928/

相关文章:

javascript - 使用 chart.js 和 bootstrap 调整 y 轴的长度

javascript - JQuery中如何获取父<a>标签元素的文本值

javascript - 你如何找到伪元素的坐标?

jquery - 如何将类更改为 html 表格中当前悬停的单元格

css - 绝对定位按钮不会出现在固定标题上

html - FF 显示不需要的边框

html - 无法在 React 上为 HTML5 拖放获取 onDragStart 事件

html - 移动友好模板

css - Webkit Animation 在其下方打破 SVG

html - iOS 7 中的视口(viewport)单位错误