首页 > 解决方案 > 为什么 span with height: auto 和 display: inline-block parent of svg 的高度比它的 svg child 大?

问题描述

简单的问题:


问题:

为什么span得到高度= 39px(见下面的图片和片段)?

在此处输入图像描述

const svg = document.getElementById('svg1');
const svgStyle = window.getComputedStyle(svg);

const span = document.getElementById('span1');
const spanStyle = window.getComputedStyle(span);

const p = document.getElementById('p1');

p.innerHTML = `
svg width = ${svgStyle.width}
svg height = ${svgStyle.height}
span width = ${spanStyle.width}
<b>span height = ${spanStyle.height} <---- Why the height of the span is greater than the svg?</b>
`
#span1 {
  display: inline-block;
  width: auto;
  height: auto;
}

#p1 {
  white-space: pre-wrap;
}
<span id="span1">
  <svg id="svg1"
    viewBox='0 0 24 24',
    height='35px'
    width='35px'
  >
    <path d='M16.021,15.96l-2.374-2.375c-0.048-0.047-0.105-0.079-0.169-0.099c0.403-0.566,0.643-1.26,0.643-2.009   C14.12,9.557,12.563,8,10.644,8c-1.921,0-3.478,1.557-3.478,3.478c0,1.92,1.557,3.477,3.478,3.477c0.749,0,1.442-0.239,2.01-0.643   c0.019,0.063,0.051,0.121,0.098,0.169l2.375,2.374c0.19,0.189,0.543,0.143,0.79-0.104S16.21,16.15,16.021,15.96z M10.644,13.69   c-1.221,0-2.213-0.991-2.213-2.213c0-1.221,0.992-2.213,2.213-2.213c1.222,0,2.213,0.992,2.213,2.213   C12.856,12.699,11.865,13.69,10.644,13.69z'/>
  </svg>
</span>

<p id="p1"></p>

标签: htmlcsssvg

解决方案


如果您使用元素的vertical-align属性,则将是所需的高度。我很幸运地使用了svg 元素。<svg><span>bottomtop

检查vertical-align https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align上的 MDN


推荐阅读