简体   繁体   English

父级div(未设置高度)是否将高度过大了几个像素以适合子img元素的高度? 为什么?

[英]Parent div, height not set, over-sizes height by a few pixels to fit child img element height? Why?

In all major browsers : as the question states, a parent <div> container (whose height is not set) over-sizes its height to fit a child <img> element (for instance, a 300-pixel tall image that is the only thing inside the div ). 在所有主要浏览器中 :正如问题所指出的那样,父<div>容器(未设置高度)将其高度过大以适合子<img>元素(例如,唯一一个300像素高的图像) div内的内容)。 The over-sizing is usually about 3 to 5 pixels, and appears at first as img margin-bottom or div padding-bottom might look. 尺寸过大通常约为3到5像素,并且最初看起来像img margin-bottom或div padding-bottom

However, using absolute positioning, it is clearly demonstrated that the bottom of the div is below the bottom of the img by a few pixels. 但是,使用绝对定位可以清楚地表明div的底部比img的底部低几个像素。 It might not ruin a website's design, but it is a hurdle to overcome in certain situations. 它可能不会破坏网站的设计,但在某些情况下是克服的障碍。 I have made a fairly detailed fiddle demonstrating this issue here . 我做了一个相当详细的小提琴,在这里演示了这个问题

  • Why is this standard practice in web browsers? 为什么在网络浏览器中使用这种标准做法?
  • Is this meant to compensate for something? 这是为了补偿某些东西吗? It seems unnecessary. 似乎没有必要。
  • Is this a bug, or a soon-to-be antiquated feature? 这是一个错误还是即将过时的功能?

EDIT: Thanks to the answerers/commentators below, I know the reason is that an <img> is treated by default as CSS display:inline which preserves whitespace around the element. 编辑:感谢下面的答复者/注释者,我知道原因是<img>默认情况下被视为CSS display:inline ,它保留了元素周围的空格。 Changing it to display:block completely fixes the problem by eliminating whitespace around the element. 将其更改为display:block消除元素周围的空白,从而完全解决了该问题。

Notes: This over-sizing can be averted by giving the image child element a CSS property of float:left or float:right , etc., but this is a workaround , and as such is not the answer to the question. 注意:可以通过给image子元素一个CSS属性float:leftfloat:right等来避免这种过大的尺寸,但这是一种解决方法 ,因此并不是解决问题的方法。 One reason this can be problematic is if you already have other float elements layered in front of the div child image (float overlap not allowed Firefox, Opera, IE. float overlapping only seems allowed in Chrome and Safari using CSS position settings). 造成问题的一个原因是,如果您已经在div子图像的前面放置了其他float元素(不允许浮动重叠,Firefox,Opera,IE。使用CSS position设置,Chrome和Safari中仅允许float重叠)。 Thanks! 谢谢!

Add display:block to your image. 将display:block添加到图像。 I think that will fix the problem. 我认为这将解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM