CSS 浮动:清除父项不会扩展它以包含浮动的子项

CSS Floats: clear on parent does not expand it to contain floated children

在此 fiddle 中,父 <p> 标签包含一个向左浮动的 <img> 标签 float: left 但是父 <p> 标签不会扩展完全包含浮动 img 元素,尽管我在父 <p> 标签上设置了 clear:both

我知道在关闭 </p><p> 上的 overflow:auto 之前添加一个带有 clear:both 的额外 div 将完成这项工作,但我很聪明结束为什么 clear:both set on <p> tag 没有像我预期的那样工作。

任何人都可以解释这种行为吗?

.thumbnail-desc h2 {
  display: inline-block;
  background: blue;
  color: #fff;
  padding: 5px 7px;
  margin-bottom: 0;
}
.thumbnail-desc img {
  float: left;
  width: 200px;
  max-height: 200px;
  margin-left: initial;
  margin-right: 10px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  overflow: hidden;
}
.thumbnail-desc p {
  background-color: #fff;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.01);
  padding: 15px;
  font-size: 18px;
  clear: both;
  margin-bottom: 20px;
  margin-top: 0;
}
<div class="thumbnail-desc">
  <h2>Some title</h2>
  <p>
    <img src="http://i.huffpost.com/gen/1632280/images/n-VISION-200x150.jpg" alt="Our Vision">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi nihil dignissimos. Some crazy text.Some crazy text</p>
</div>

您可以为 <p> 添加 overflow: hidden;。这是示例:https://jsfiddle.net/hnL0gLy2/

看来您可能误解了 clear 的工作原理。

<p> 标签上设置 clear:both 是告诉 p 清除它之前的所有内容 - 而不是其中的子项。

不要使用 p 标签覆盖图像,而是使用 classdiv

Fiddle.

HTML:

<div class="thumbnail-desc">
<h2>Some title</h2>
<div class="outer">
<img src="http://i.huffpost.com/gen/1632280/images/n-VISION-200x150.jpg" alt="Our Vision">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi nihil dignissimos. Some crazy text.Some crazy text
</div>
</div>

CSS:

.thumbnail-desc h2 {  display: inline-block;
            background: blue;
            color: #fff;
            padding: 5px 7px;
            margin-bottom: 0; }

.thumbnail-desc img {
     float: left;
    width: 200px;
    max-height: 200px;
    margin-left: initial;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    overflow: hidden; }
.thumbnail-desc .outer {
    background-color: #fff;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.01);
    padding: 15px;
    font-size: 18px;
    height:150px;
    }

为什么你的代码没有像你想的那样工作?

因为 p 标签用于文本。它的高度与 div 中的文本一样多。要获得更高的高度,您需要切换到 divspan

您需要将 .thumbnail-desc p 设置为 inline-blockdisplay