Dan*_*obe 7 html css centering flexbox
justify-content因此,垂直居中的文本看起来很简单,align-items但当我仔细观察时,我发现文本并没有真正居中。字符顶部的间距较小。我尝试通过在线搜索进一步调查,发现了这个https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align但必须有一个更简单的解决方案。
示例 https://jsfiddle.net/z7cy487o/
html,
body {
height: 100%;
}
.box {
height: 10%;
width: 400px;
background: #000;
font-size: 11vh;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
}Run Code Online (Sandbox Code Playgroud)
<div class="box">
C
</div>Run Code Online (Sandbox Code Playgroud)
您的感知方式取决于您使用的角色。我将您的示例复制了两次以显示不同的情况:
在第二个版本中,我只使用了字母“y”,它有一个下降部分,即延伸到基线以下的部分,到定义为 的区域的下边界line-height。另一方面,它并没有完全上升,因此在垂直对齐方面,它似乎与第一个版本(字母“C”)完全相反。
在第三个版本中,我将这两个字母组合成一个单词。在这里您可以看到不同的字符/字母在一起确实延伸到整个宽度,因此垂直居中是正确的。
行高(以及与之相关的字母的垂直对齐)并不取决于使用哪个字母 - 它始终适用于所有可能的字母/字符,即使它们在特定情况下不使用。
html, body { height: 100%; }
.box
{
height: 10%;
width: 400px;
background: #000;
font-size: 11vh;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
}Run Code Online (Sandbox Code Playgroud)
<div class="box">
C
</div>
<div class="box">
y
</div>
<div class="box">
Cyborg
</div>Run Code Online (Sandbox Code Playgroud)
Dan*_*obe -2
该解决方案基于圆内垂直和水平的中心文本字符 \xe2\x98\xa2 (CSS)的修改版本\n它似乎适用于动态高度,但正如 Johannes 在他的答案的评论中提到的那样。我相信该解决方案仅适用于我的情况。
\n\nhtml,\r\nbody {\r\n height: 100%;\r\n}\r\n\r\n.box {\r\n height: 10%;\r\n width: 400px;\r\n background: #000;\r\n font-size: 11vh;\r\n color: #FFF;\r\n text-align: center;\r\n padding: 0 20px;\r\n margin: 20px;\r\n display: flex;\r\n justify-content: center; /* align horizontal */\r\n align-items: center; /* align vertical */\r\n}\r\n\r\n.char {\r\n line-height: 1px;\r\n font-family: sans-serif;\r\n font-weight: 500;\r\n position: relative;\r\n top: 0.05em;\r\n}Run Code Online (Sandbox Code Playgroud)\r\n<div class="box">\r\n <span class="char">C</span>\r\n</div>Run Code Online (Sandbox Code Playgroud)\r\n