html - float 容器内图像的奇怪行为

标签 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>

CSS

.container {
  height: 20vh;
}

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

img {
  height: 100%;
}


问题#1

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

enter image description here

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

enter image description here


问题 #2

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

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

enter image description here


请参阅此 Fiddle 中的行为.

问题:是否可以添加一种样式,使所有浏览器的行为一致?

[注意:我在研究 this question 时发现了这一点.我以为我有一个解决方案,直到我意识到它在除 Firefox 之外的任何浏览器中都没有响应。]

最佳答案

以下可能会成功。

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

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

.imgContainer.panel 这两个子元素,使用display: table-cell 并继承父 block 的高度.

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

.container {
  height: 20vh;
  display: table;
}
.imgContainer, .panel {
  display: table-cell;
  height: inherit;
  vertical-align: top;
}
img {
  vertical-align:top;
  height: inherit;
}
<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>

关于html - float 容器内图像的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112463/

相关文章:

html - 如何阻止背景颜色渐变重复? (CSS)

html - 属性 'font-size' 也会改变 'background-img' 的大小

css - 如何将右列 div 设置为固定(当前 "postition: fixed"使部分移动到左侧)

html - 在 IE 中打开 tiff 图像

javascript - 为什么此警报不适用于 javascript?

javascript - 如何在Javascript中滑动到另一个html页面?

css - 垂直对齐包含页眉和页脚的 flexbox 子项中的内容

jquery - Metro UI CSS - 下拉菜单不起作用

javascript - 尝试从 javascript 获取数据然后在 HTML 中显示时出错

php - 表单文本区域不超过一行,只是不断滚动