我在 DIV 和 BUTTON 元素内有一个 SVG 元素。在 Button 中,它垂直和水平居中对齐,在 DIV 中,它顶部和左侧对齐。
我已经检查了这两个元素,但找不到使 SVG 在 BUTTON 中居中对齐的原因。用户代理样式表中一定有一些东西,但我找不到它。
这是代码和演示:
<button>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path d="M21.99 4c0-1.1-.89-2-1.99-2h-16c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"></path>
<path d="M0 0h24v24h-24z" fill="none"></path>
</svg>
</button>
<div>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path d="M21.99 4c0-1.1-.89-2-1.99-2h-16c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"></path>
<path d="M0 0h24v24h-24z" fill="none"></path>
</svg>
</div>
button, div {
padding: 0;
margin: 8px;
width: 44px;
height: 44px;
border: 1px solid;
background-color: transparent;
}
button svg, div svg {
padding: 0;
margin: 0;
}
如果您在浏览器的开发工具中检查按钮,您将能够看到浏览器默认应用于按钮等元素的用户代理 CSS 规则(您可能需要启用此选项)。例如,在 Chrome 中,您会在
text-align: center
的 CSS 属性中找到 <button>
。然而,由于一个元素在另一个元素中的垂直居中无法通过标准 CSS 技巧框来完成,因此您找不到任何属性可以做到这一点。 AFAIK 这是浏览器为按钮所做的一件特殊的事情。
有一些技巧可以让您做到这一点,例如使用
display: table-cell;
,但是,就您而言,最简单的解决方案是让 SVG 引擎为您做这件事。只需使用 text-align: center
进行水平居中,并将 SVG 高度设置为 <div>
高度,SVG 引擎将完成剩下的工作。
button, div {
...
text-align: center;
}
div svg {
height: 44px;
}