为什么容器 div 坚持要略大于 IMG 或 SVG 内容?

我正在尝试生成另一个 lightbox,因为这是很需要的 HTML/CSS/Javascript 实践,但是我遇到了一个样式问题,这个问题看起来微不足道(可能确实如此!)但我就是解决不了。

我有一个包含 imgdiv。无论我尝试(bordermarginpadding,自动高度等)我只是不能使 div收缩匹配图像尺寸。我把问题简化成这样:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Layout experiments</title>


<style type="text/css">
#lightbox {
margin: 0;
padding: 0;
position    : fixed;
left        : 50%;
margin-left : -320px;
top         : 100px;
border-radius: 22px;
background  : #e0e0f0;
color       : #102020;
}


#lightbox img {
border-radius: 15px;
}
.imagebg {
margin      : 7px;
background  : black;
border-radius: 15px;
height      : 100%;
}


</style>


</head>
<body>


<div id="lightbox">
<div class="imagebg">
<img src="picture.jpg">
</div>
</div>
</body>
</html>

Jpg 是640x400,但容器 div 希望是640x404,差异显示为图像下方的黑条。Div 的存在使我可以通过将图像的不透明度混合为0来淡化为黑色,然后交换它,然后再混合回来。

我查看了多个浏览器中的计算样式,看不出4px 增量是从哪里来的。

40594 次浏览

Trying adding:

img { display: block; }

to your CSS. Since an <img> is an inline element by default, its height is calculated differently as related to the default line-height value.

On inline elements, the line-height CSS property specifies the height that is used in the calculation of the line box height.

On block level elements, line-height specifies the minimal height of line boxes within the element.

Source: https://developer.mozilla.org/en/CSS/line-height

Your image is using the line-height of its parent. Try this:

.imagebg { line-height: 0 }

Basically you are getting this error on IE, though you hve not mentioned but this is the fact. IE generates some extra space below the <img> tag. Hence its a good practice to make the images img { display: block; }.

EDIT: You can say its a bug of IE

If you don't want to change display of the element, try

margin-bottom: -4px;

try adding:

vertical-align: middle;

This is used in google material design lite for removing the gap between audio, canvas, iframes, images, videos and the bottom of their containers.

Material Design Lite: https://getmdl.io

Github discusion: https://github.com/h5bp/html5-boilerplate/issues/440

Apart from other working answers, setting display property of parent to flex worked for me as well:

.imagebg { display: flex }