图像在浮动容器内的奇怪行为

Ric*_*ock 6 html css

鉴于这种简单的布局:

HTML

<div class="container">
  <div class="imgContainer">
    <img src="http://placehold.it/400x400">
  </div>
  <div>
    This should always stay to the right of the image.
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.container {
  height: 20vh;
}

.imgContainer {
  float: left;
  height: 100%;
}

img {
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)


问题#1

Chrome,Firefox和Opera正确显示如下:

在此输入图像描述

IE11根据图像的自然宽度错误地将文本放置在右侧400像素:

在此输入图像描述


问题#2

当您增加窗口的高度时,文本应保持粘在图像的右侧.这在Firefox中可以正常工作.

但是,文本与Chrome和Opera中的图像重叠:

在此输入图像描述


看看这个小提琴中的行为.

问题: 我可以添加哪种样式会导致所有浏览器的行为一致吗?

[注意:我在处理这个问题时发现了这一点.我以为我有一个解决方案,直到我意识到除了Firefox之外的任何浏览器都没有响应.

Mar*_*det 1

下面的方法也许能解决问题。

float我建议使用 CSS 表,而不是使用。

display: table根据需要应用.container并设置高度。

对于两个子元素.imgContainer.panel,使用display: table-cell并继承父块的高度。

我认为这非常接近您所需要的,应该适用于所有浏览器(但我没有检查......)

.container {
  height: 20vh;
  display: table;
}
.imgContainer, .panel {
  display: table-cell;
  height: inherit;
  vertical-align: top;
}
img {
  vertical-align:top;
  height: inherit;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="imgContainer">
    <img src="http://placehold.it/400x400">
  </div>
  <div class="panel">
    This should always stay to the right of the image.
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)