这个问题类似于此前解决的问题:CSS text-align delay with width animation
我有一个从0%宽度到100%的动画,目的是加载页面而不显示任何文本,并立即从左到右显示它。
我注意到,在包含填充的情况下,左侧文本的第一部分已经可见。这是什么原因?谢谢!
@keyframes leftright {
0% {
max-width: 0%;
}
100% {
max-width: 100%;
}
}
.test_1 {
overflow: hidden;
white-space: nowrap;
width: 80vw;
padding: 0 10vw;
border: 1px solid red;
font: bold 15vmin 'Playfair Display', serif;
animation: leftright 1s;
}
<div class="test_1">Why hello there</div>
通过拆分演示文稿和动画作业并将它们分配给单独的div,您可以实现所需的行为,而不会产生不必要的副作用。
这是另一个问题,它可以解释为什么填充div的宽度不为零。 border-box with padding can't have 0 width
@keyframes leftright {
0% {
max-width: 0%;
}
100% {
max-width: 100%;
}
}
.test_1 {
animation: leftright 10s;
overflow: hidden;
white-space: nowrap;
width: 80vw;
border: 1px solid red;
}
.test_2 {
padding: 0 10vw;
font: bold 15vmin 'Playfair Display', serif;
}
<div class="test_1">
<div class="test_2">Why hello there</div>
</div>
这是因为CSS width
属性(以及max-width
和min-width
属性)指的是content width。内容是box model中的边距,边框和填充内的内容。
如果你看一下div.test_1
的起始属性,它们是:
.test_1 {
overflow: hidden;
white-space: nowrap;
padding: 0 10vw;
max-width: 0;
border: 1px solid red;
font: bold 15vmin 'Playfair Display', serif;
}
<div class="test_1">Why hello there</div>
元素的可视宽度实际上是由于宽度加上10vw
的左右填充值,加上左右边框宽度。
要解决它,你可以做JasonB建议的事情。
或者,您可以在keyframes
中包含填充,这也具有动画(左和右)填充的副作用。
@keyframes leftright {
0% {
padding: 0;
max-width: 0;
}
100% {
padding: 0 10vw;
max-width: 100%;
}
}
.test_1 {
overflow: hidden;
white-space: nowrap;
/* width: 80vw; <-- I removed this as it appears to contradict with max-width */
border: 1px solid red;
font: bold 15vmin 'Playfair Display', serif;
max-width: 100%;
padding: 0 10vw;
animation: leftright 1s;
}
<div class="test_1">Why hello there</div>