为什么当我输入时我的 h1 没有出现在屏幕中间:
h1 {
margin-top: calc((100%)/2);
transition: color 0.5s linear, transform 0.5s ease-in-out;
}
(说到margin-top属性)
相反,它显示在屏幕底部,有人可以解释一下原因吗?
最佳答案
margin 百分比为 always based on width .
flexbox
使用flexbox可以达到想要的效果,如下图。
/* Remember that containers' heights are a percentage of their parents' heights */
html, body {
padding: 0;
margin: 0;
height: 100%;
}
.container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
h1 {
flex: 0 0 auto;
vertical-align: middle;
}
<div class="container">
<h1>Hello World</h1>
</div>
备选
Flexbox 支持非常复杂的场景,但对于这种特殊情况有一种更简单的方法,即使用 vh
(视口(viewport)高度)单位。
h1 {
font-size: 24px;
line-height: 32px;
margin-top: calc(50vh - 16px);
}
<h1>Hello World</h1>
附加说明
我不确定你为什么在你的例子中使用 calc()
,但如果你这样做,一定要输入 spaces around the operators .除法运算符不需要空格,但进入是个好习惯。
关于html - 为什么 css "margin-top: calc((100%)/2)"的 h1 元素显示在屏幕底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119715/