这里介绍了您的第二个案例:Image inside div has extra space below the image。由于默认对齐方式,您的 SVG 下方将有额外的空间。这可以通过像您发现的那样添加 display:block 或添加 vertical-align:top 来解决,这作为解决方案更合乎逻辑:
span {
display: block;
padding: 15px;
outline:1px solid green;
}
div {
height: 50px;
width: 50px;
margin:30px;
outline:1px solid blue;
}
svg {
height: 20px;
width: 20px;
outline:1px solid red;
}
<div>
<span>
<svg
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
</div>
<div>
<span>
<svg
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg" style="vertical-align:top;"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
</div>
您的第一种情况有点棘手,因为它与 SVG 或您设置的宽度/高度无关。都是关于字体指标的。
为简化起见,让我们删除周围的 div 并考虑在同一 span 内使用不同的 SVG 并且没有填充:
span {
border: 1px solid green;
margin:0 10px;
}
svg {
outline: 1px solid red;
}
<span>
<svg
viewBox="0 0 24 24" height="20"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
<span>
<svg
viewBox="0 0 24 24" height="30"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
<span>
<svg
viewBox="0 0 24 24" height="50"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
<span>
<svg
viewBox="0 0 24 24" height="200"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
请注意,由于内联元素的性质,跨度如何始终保持相同的高度,而不管 SVG 内部如何。让我们增加font-size
span {
border: 1px solid green;
margin:0 10px;
}
svg {
outline: 1px solid red;
}
body {
font-size:40px;
}
<span>
<svg
viewBox="0 0 24 24" height="20"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
<span>
<svg
viewBox="0 0 24 24" height="30"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
<span>
<svg
viewBox="0 0 24 24" height="50"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
<span>
<svg
viewBox="0 0 24 24" height="200"
xmlns="http://www.w3.org/2000/svg"
>
<circle
strokeLinecap="butt"
strokeDasharray="64"
cx="12"
cy="12"
r="9"
/>
</svg>
</span>
现在跨度的高度更大,SVG 保持不变。由于我之前解释过的对齐方式,您还会注意到 SVG 底部的小间隙。尝试添加font-size:0 看看结果。
如您所见,跨度的高度与 SVG 无关。对于该高度,您添加垂直填充以获得最终高度。在您的情况下,高度为 17px 并添加填充您将拥有 47px 接近 50px 但没有关系。
请注意,如果您在不同的浏览器/操作系统中进行测试,您可能会得到与 47px 不同的结果,因为字体不一定相同,并且初始高度可能会有所不同。
如果您查看the speficiation,您可以阅读:
“高度”属性不适用。内容区域的高度应根据字体 ...
内联非替换框的垂直内边距、边框和边距从内容区域的顶部和底部开始,
制作 span 块元素将改变这种行为,您将获得更直观的结果,正如您在上一个示例中注意到的那样:2*15px 的填充 + 20px 的 SVG 高度。
更详细的相关问题,以了解如何计算元素的高度:How to determine height of content-box of a block and inline element
另一个相关问题:Can specific text character change the line height?