我创建了一个小片段来说明问题。
我在svg
标记中有一个<i>
图标。这是我图标的基本块,放置在我页面的各个位置。为了这个示例,我将其放置在一个简单的div容器中。
如果检查以下示例的结果,则可以看到<i>
标签的高度为33px
,而不是预期的30px
。我的问题是为什么会发生这种情况以及如何预防呢?
.container {
font-size: 30px;
}
.icon {
line-height: 1;
}
.icon svg {
height: 1em;
width: 1em;
}
<div class="container">
<i class="icon">
<svg width="24" height="24" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>
</i>
</div>
答案 0 :(得分:3)
为防止这种情况,请i
内联代码块并更正SVG的对齐方式。
.container {
font-size: 30px;
height: 30px;
width: 30px;
}
.icon {
line-height: 1;
display:inline-block;
}
.icon svg {
height: 1em;
width: 1em;
vertical-align:top;
}
<div class="container">
<i class="icon">
<svg width="24" height="24" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>
</i>
</div>
为什么有点棘手,并且与字体有关。基本上,作为行内元素的i
的高度取决于字体属性,并且设置line-height:1
是不够的
为了更好地说明:
$('i').each(function(){
console.log("i element: "+$(this).css('height')+" SVG: "+ $(this).find('svg').css('height'));
})
.container {
font-size: 30px;
height: 30px;
width: 30px;
line-height: 0;
margin:10px;
}
.icon {
line-height: 0;
background:green;
}
.icon svg {
height: 1em;
width: 1em;
vertical-align:top;
background:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<i class="icon">
<svg width="24" height="24" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>
</i>
</div>
<div class="container" style="font-family:monospace">
<i class="icon">
<svg width="24" height="24" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>
</i>
</div>
<div class="container" style="font-family:cursive">
<i class="icon">
<svg width="24" height="24" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>
</i>
</div>
如您所见,我们拥有相同的font-size
,并且line-height
设置为0
,而我们仍然拥有较大的i
,因为它代表了内容我们无法控制的区域。
此处有更多详细信息:Can specific text character change the line height
也相关:Line height issue with inline-block elements可以更好地了解line-height
的工作原理,因为它并不总是直观的。
另一种显示行框和内容区域之间的区别的方法:Why is there space between line boxes, not due to half leading?