html - 为什么 float 在父容器中会改变 img 的大小?

标签 html css

我有一个容器和里面的图像。当父级被赋予 float 时,子级的高度不匹配。当两者都被赋予 float 时,它匹配。为什么?

 <div class="parent"><img src="images/trest.png" class="image"></img></div>

在以下情况下不匹配:

.parent{
float:left;
}
.image{}

完美的时候:

.parent{
    float:left;
    }
    .image{
    float:left;
    }

enter image description here

最佳答案

基本上,使用float 指定元素将in most cases将它变成一个 block 元素。

默认情况下,当放置在 block 级容器中时,图像元素会出现下面不需要的空白区域的问题。解决方案通常是将图像元素的显示设置为 block

来自 MDN :

As float implies the use of the block layout, it modifies the computed value of the display values in some cases:

floatdisplay:block的比较(本质上结果是一样的):

.parent {
  float: left;
  border: 2px solid red;
}
.image {
  border: 2px solid blue;
}
.image2 {
  border: 2px solid blue;
  display: block;
}
.image3 {
  border: 2px solid blue;
  float: left;
}
<div class="parent"><img src="https://placehold.it/100x100" class="image"/></div>
<div class="parent"><img src="https://placehold.it/100x100" class="image2"/></div>
<div class="parent"><img src="https://placehold.it/100x100" class="image3"/></div>

关于html - 为什么 float 在父容器中会改变 img 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37324206/

相关文章:

html - 在 Ionic 4.0 中更改 ionic 项背景颜色

html - 为什么我的 contentEditable 元素在 Firefox 中变得可拖动/可调整大小?

javascript - 改变侧边栏的颜色

jquery - 如何将一个 div 放置在另一个 div 的右侧,但又不占用空间?

html - 如何在html5中 float 部分标签

html - 使用 Bootstrap 按钮滚动到不同区域

javascript - PHP - HTML5 API 上传损坏

javascript - swiper.js - 幻灯片更改时的幻灯片 CSS 动画问题

html - 需要在不同的 div 中垂直对齐 p 标签

css - 为什么 Firefox 渲染的虚线边框彼此不对齐?