RNo*_*bel 2 html css fonts svg
我在这样的元素中包含一个svg元素h1:
<h1>
64px ABC
<span class="icon">
<svg width="64" height="64" viewBox="0 0 64 64">
<rect id="block" x="4" y="4" width="56" height="56" rx="16" ry="16" stroke-width="1" />
</svg>
</span>
xyz
</h1>
Run Code Online (Sandbox Code Playgroud)
然后,我将图标定位得稍低一些,以便使用相对定位与文本很好地对齐。
h1 {
font-size: 64px;
}
.icon {
position: relative;
top: 0.14453125em; /* Calculated using https://seek-oss.github.io/capsize/ */
}
svg {
height: 1em;
fill: currentColor;
}
Run Code Online (Sandbox Code Playgroud)
这一切都有效,但在高度为 1em 时,其父元素的svg值会增加。height
这是h1没有的svg:

这是包含在内svg的:

相差5px。
当我将高度更改为例如 0.9em 时,这种情况不会发生。
我尝试了许多不同的选项,但没有达到预期的结果 - 保持父元素的高度不变。
为什么会发生这种情况?我们如何确保不会发生这种情况?
代码笔: https: //codepen.io/denobelsoftware/pen/MWjKKXO
<h1>
64px ABC
<span class="icon">
<svg width="64" height="64" viewBox="0 0 64 64">
<rect id="block" x="4" y="4" width="56" height="56" rx="16" ry="16" stroke-width="1" />
</svg>
</span>
xyz
</h1>
Run Code Online (Sandbox Code Playgroud)
h1 {
font-size: 64px;
}
.icon {
position: relative;
top: 0.14453125em; /* Calculated using https://seek-oss.github.io/capsize/ */
}
svg {
height: 1em;
fill: currentColor;
}
Run Code Online (Sandbox Code Playgroud)
let iconsHidden = false;
const elements = document.querySelectorAll(".icon");
document.querySelector("#hide-icons").addEventListener('click', function(event) {
for (var i = 0; i < elements.length; i++) {
if(iconsHidden){
elements[i].classList.add('hidden');
} else elements[i].classList.remove('hidden');
}
iconsHidden = !iconsHidden;
});Run Code Online (Sandbox Code Playgroud)
制作跨度display:inline-block并添加vertical-align:top以避免默认基线对齐,这将使行框更大,然后也用于line-height:0确保内部的 svg 不会影响其大小。那么你可能需要重新调整顶部值:
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700&display=swap');
h1 {
font-size: 64px;
font-family: 'Roboto', sans-serif;
font-weight: normal;
position: relative; /* for the rulers */
}
.icon {
position: relative;
top: 0.14453125em;
display:inline-block;
vertical-align:top;
line-height:0;
}
svg {
height: 1em;
fill: currentColor;
}
h1:after{
width: 100%;
height: 1px;
content: "";
position: absolute;
bottom: 0.244140625em;
left: 0;
background-color: rgba(255, 0, 0, 0.23);
z-index: -100;
}
h1:before{
width: 100%;
height: 1px;
content: "";
position: absolute;
bottom: 0.955078125em;
left: 0;
background-color: rgba(255, 0, 0, 0.23);
z-index: -100;
}
.hidden {
display: none;
}Run Code Online (Sandbox Code Playgroud)
<body>
<h1>
64px ABC
<span class="icon">
<svg width="64" height="64" viewBox="0 0 64 64" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect id="block" x="4" y="4" width="56" height="56" rx="16" ry="16" stroke-width="1" />
</svg>
</span>
xyz
</h1>
<h1>
64px ABC
xyz
</h1>
<input type="checkbox" id="hide-icons">
<label for="hide-icons"> Hide icons</label>
</body>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
790 次 |
| 最近记录: |