CSS——边框过渡效果
今天浅浅的水一下边框过渡效果。
按钮边框过渡效果
小小的解释一波
这里采用了一个外围的容器盒子,为了实现容器盒子的水平居中(这个简单)和垂直居中(这个就稍微复杂一些,往后可能会出一期专门设置垂直居中的文章),我还是请出了 Flex弹性盒子 ,真的是太好用了。
这里将body设置为弹性容器,然后再通过弹性容器 justify-content
和 align-items
分别实现水平和垂直居中。不是很了解的同学可以查看 CSS——弹性盒子布局(display: flex),里面内容很详细。
display: flex;
justify-content: center;
align-items: center;
这时候发现,容器里面的按钮是如何对齐的呢?这里我想让弹性盒子歇一歇。然后我就投机取巧地设置父盒子是按钮的三倍大小(宽高都是等比例的),这样的话,我只需要将按钮水平、竖直地移动自身长度地100%,就可以实现水平和垂直的居中了。(虽然可行,但是不推荐)
.container {width: 360px;height: 216px;text-align: center;}.button {position: relative;width: 120px;height: 72px;translate: 100% 100%;line-height: 72px;}
关键的动画效果是如何制作的呢?
这里我首先创建了按钮地两个伪元素,然后对伪元素进行操作,这里采用了clip-path
属性,其具体使用可以参考MDN(inset()函数),这里我使用inset()
裁剪出了矩形区域,其中的值是确保初始时候每条边上的线长都为30px。
.button::before {clip-path: inset(0 90px 42px 0);
}.button::after {clip-path: inset(42px 0 0 90px);
}
然后使用伪类在鼠标悬停时做出改变
.button:hover::before {clip-path: inset(0 0 0 0)
}.button:hover::after {clip-path: inset(0 0 0 0)
}
为了实现平滑过渡,我们为伪元素添加了动画延时效果
transition: 1s ease;
源代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>边框过渡</title><style>* {padding: 0;margin: 0;}a {text-decoration: none;color: #fff;font-size: 1.5rem;}body {width: 100vw;height: 100vh;background-image: radial-gradient(circle at center, rgba(10, 10, 10, 0.5), #000);display: flex;justify-content: center;align-items: center;}.container {width: 360px;height: 216px;text-align: center;}.button {position: relative;width: 120px;height: 72px;translate: 100% 100%;line-height: 72px;}.button::before,.button::after {box-sizing: border-box;content: '';width: 120px;height: 72px;border: 1px solid #fff;position: absolute;top: 0px;left: 0px;transition: 1s ease;}.button::before {clip-path: inset(0 90px 42px 0);}.button::after {clip-path: inset(42px 0 0 90px);}.button:hover::before {clip-path: inset(0 0 0 0)}.button:hover::after {clip-path: inset(0 0 0 0)}</style>
</head><body><main class="container"><div class="button"><a href="javascript:;">按钮</a></div></main>
</body></html>