情况如下:
body {
margin: 0;
background: pink;
color: #fff;
}
.box {
margin-top: 20px;
background: red;
}
.bottom {
text-align: right;
background: green;
animation: animate 2s infinite alternate linear;
}
@keyframes animate {
from {
margin-top: 10px;
}
to {
margin-top: -40px;
}
}Run Code Online (Sandbox Code Playgroud)
<div class="box">
some content
</div>
<div class="bottom">
other content
</div>Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我们有两个div没有任何复杂样式(简单的背景颜色).我div通过应用否定来使第二个与第一个重叠margin-top.我期待看到一个完全重叠另一个,但事实并非如此.第二个div是在第一个内容和背景之间滑动,对我来说这是一个奇怪的行为.
这里的动画无关,我只是用它来更好地展示行为.我们可以简单地添加负边距而不用动画,我们会有同样的事情:
body {
margin: 0;
background: pink;
color: #fff;
}
.box { …Run Code Online (Sandbox Code Playgroud)请考虑以下代码段:
html {
margin: 0;
padding: 0;
background-color: blue;
}
body {
margin: 0;
padding: 0;
background-color: green;
min-height: 100vh;
}Run Code Online (Sandbox Code Playgroud)
<section style="min-height: 50px; background-color: pink;"></section>Run Code Online (Sandbox Code Playgroud)
正如所料,body元素以绿色填充整个视口,顶部有一个粉红色的section元素.
现在,假设你想做一些非常简单的事情,比如在section元素中设置一个边距:style="min-height: 50px; background-color: pink; margin-bottom: 10px;".出乎意料的是,html元素中的蓝色条带出现在视口的底部.
html {
margin: 0;
padding: 0;
background-color: blue;
}
body {
margin: 0;
padding: 0;
background-color: green;
min-height: 100vh;
}Run Code Online (Sandbox Code Playgroud)
<section style="min-height: 50px; background-color: pink; margin-bottom: 10px;"></section>Run Code Online (Sandbox Code Playgroud)
问题1)为什么会这样?这对我来说没有意义.
纠正此行为的一种方法是min-height在body元素中包含padding和calc()调整:
html {
margin: 0;
padding: 0;
background-color: blue;
}
body {
margin: 0; …Run Code Online (Sandbox Code Playgroud)