【问题标题】:Transition HTML element from center in CSS3在 CSS3 中从中心转换 HTML 元素
【发布时间】:2018-09-15 02:10:59
【问题描述】:
我正在尝试使用 CSS 为元素的高度属性设置动画,但我希望它从中心开始。下面是我的代码,但它从底部改变了高度。
.toggle {
position: absolute;
width: 400px;
height: 200px;
background: #ccc;
}
.left-border {
position: absolute;
top: 50px;
left: 10px;
width: 20px;
height: 60px;
border-radius: 200px;
background-color: #ff0000;
animation: height 2s;
}
@-webkit-keyframes height {
from {
height: 60px;
}
to {
height: 10px;
}
}
<div class="toggle">
<div class="left-border"></div>
</div>
这里是JSFIDDLE
【问题讨论】:
标签:
html
css
css-transitions
css-animations
【解决方案1】:
您可以使用transform
from {
}
to {
transform: scaleY(0.1666);
}
0.1666 来自10px / 60px
【解决方案2】:
给你。我使用动画top 而不是height。红色开关现在也需要一个“容器”,所以我只使用了你那里的那个。更改红色切换的尺寸时,更改外包装,而不是切换元素(它将适合任何容器,无论是宽度还是高度)
https://jsfiddle.net/j2refncs/7/
.toggle {
width: 20px;
height: 40px;
background: #ccc;
position: relative;
.left-border {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
border-radius: 200px;
background-color: #ff0000;
animation: height 2s;
}
}
@-webkit-keyframes height {
from {
top: 0;
}
to {
top: 30px;
}
}
【解决方案3】:
只需将top: 75px 添加到关键帧,因为height 的变化是50px。您希望将height 从两侧(top 和 bottom)减少 25px 或一半,以达到所需的10px。所以 50px / 2 + top: 50px = top: 75px:
.toggle {
position: absolute;
width: 400px;
height: 200px;
background: #ccc;
}
.left-border {
position: absolute;
top: 50px; /* starting position from the top */
left: 10px;
width: 20px;
height: 60px;
border-radius: 200px;
background-color: #f00;
animation: height 2s;
}
@-webkit-keyframes height {
to {height: 10px; top: 75px} /* + ending position from the top */
}
<div class="toggle">
<div class="left-border"></div>
</div>
【解决方案4】:
您可以使用height 为top 设置动画,以使高度变化从中心出现:
.toggle {
position: relative;
width: 400px;
height: 200px;
background: #ccc;
}
.left-border {
position: absolute;
top: 25px;
left: 10px;
width: 20px;
height: 60px;
border-radius: 200px;
background-color: #ff0000;
animation: height 2s forwards;
}
@keyframes height {
from {
top: 25px;
height: 60px;
}
to {
top: 50px;
height: 10px;
}
}
<div class="toggle">
<div class="left-border"></div>
</div>
您也可以在动画中使用transform: scaleY()。默认transform origin 为中心。
.toggle {
position: relative;
width: 400px;
height: 200px;
background: #ccc;
}
.left-border {
position: absolute;
top: 25px;
left: 10px;
width: 20px;
height: 60px;
border-radius: 200px;
background-color: #ff0000;
animation: height 2s forwards;
}
@keyframes height {
from {
transform: scaleY(1);
}
to {
transform: scaleY(0.167);
}
}
<div class="toggle">
<div class="left-border"></div>
</div>