一个p里面有两个元素img span.
1。在p上设置font-size:0px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> relationship between height and font-size </title>
<style type="text/css">
*{
margin:0px;
border:0px;
box-sizing:border-box;
}
p{
border:1px solid black;
font-size:0px;
}
img{
border:1px solid red;
}
span{
border:1px solid blue;
}
</style>
</head>
<body>
<p>
<img src="https://i.stack.imgur.com/abMWp.jpg" alt=""><span>it is a car</span>
</p>
<script language="JavaScript">
var e1=document.getElementsByTagName("p")[0];
var e2=document.getElementsByTagName("img")[0];
alert("Target height is "+(e1.offsetHeight-e2.offsetHeight).toString());
</script>
</body>
</html>
保存为car1.html,运行结果是0.
2。在p的两个子元素上设置font-size:0px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> relationship between height and font-size </title>
<style type="text/css">
*{
margin:0px;
border:0px;
box-sizing:border-box;
}
p{
border:1px solid black;
}
img{
border:1px solid red;
font-size:0px;
}
span{
border:1px solid blue;
font-size:0px;
}
</style>
</head>
<body>
<p>
<img src="https://i.stack.imgur.com/abMWp.jpg" alt=""><span>it is a car</span>
</p>
<script language="JavaScript">
var e1=document.getElementsByTagName("p")[0];
var e2=document.getElementsByTagName("img")[0];
alert("Target height is "+(e1.offsetHeight-e2.offsetHeight).toString());
</script>
</body>
</html>
保存为car2.html,运行结果是6px.
请问,如何解释这种行为?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是font-size对img标签的影响。外层包围img元素的p font-size越大,底部留白也就越大。span作为一个行内元素,高度没有img高,可以忽略。e1和e2之间相差的高度就是img和p之间的留白。(当然你要border注释掉,p font-size:0时才能得到e1-e2等于0)。
指出一点:情况1应该为2
三个点:
1.p的高度是由
line-height撑起。2.默认情况下,
line-height为normal(1.1-1.2由浏览器决定),又是由font-size决定3.
offsetHeight还包括border所以,我们再来看:
情况1:在父元素
p设置font-size:0;此时,span继承font-size:0,但border上下和2px,所以,p的offsetHeight=内容高度+border,内容高度=img的offsetHeight+span的2px,所以e1.offsetHeight-e2.offsetHeight=2才对情况2:在子元素上分别设置
font-size:0;img和span的情况和上述一样,但是p的font-size默认为16px;line-height值由浏览器决定,所以它的内容高度改变了,最后的值由浏览器决定。