如何用纯 CSS 创作一把剪刀

前端阳光

共 4614字,需浏览 10分钟

 ·

2021-03-27 08:06

问:如何用纯 CSS 创作一把剪刀


动态效果预览


复制跳转下方连接可以去查看动态效果

https://codepen.io/comehope/pen/GXyGpZ

源代码下载

https://github.com/comehope/front-end-daily-challenges

代码解读

定义 dom,容器中包含 2 个 .half 元素,各表示剪刀的半边,它的子元素 handle 表示刀柄,blade 表示刀,最后的 .joint 表示连接左右两部分铆钉:

<figure class="scissors">
    <div class="half">
        <span class="handle"></span>
        <span class="blade"></span>
    </div>
    <div class="half">
        <span class="blade"></span>
        <span class="handle"></span>
    </div>
    <div class="joint"></div>
</figure>

居中显示:

body {
    margin0;
    height100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

定义容器尺寸,其中 outline 是辅助线:

.scissors {
    width21em;
    height7em;
    outline1px dashed;
}

定义半边剪刀的尺寸,其中 outline 是辅助线:

.scissors {
    position: relative;
}

.half {
    position: absolute;
    width: inherit;
    height4em;
    outline1px dashed red;
}

画出刀柄:

.handle {
    position: absolute;
    box-sizing: border-box;
    width8em;
    height: inherit;
    border1em solid #333;
    border-radius2em;
}

画出刀,用圆角属性画出了顶部的刀尖:

.blade {
    position: absolute;
    width15em;
    height1em;
    background-color: silver;
    top3em;
    left6em;
    border-radius0 0 1em 0;
    z-index: -1;
}

用伪元素在刀的底部画一个三角形,使刀与刀柄连接得更牢固:

.blade::before {
    content'';
    position: absolute;
    border-style: solid;
    border-width0 1.8em 1em 1.8em;
    border-color: transparent transparent silver transparent;
    top: -1em;
    left0.2em;
}

使半边刀倾斜:

.half {
    transform-origin45% bottom;
    transformrotate(15deg);
}

利用 scale() 函数画出剪刀的另一半:

.half {
    transform-origin45% bottom;
    transformrotate(calc(15deg * var(--direction))) scaleY(var(--direction));
}

.half:nth-child(1) {
    --direction1;
    top0;
}

.half:nth-child(2) {
    --direction: -1;
    top: -1em;
}

画出连接左右半边的铆钉:

.joint {
    position: absolute;
    width0.7em;
    height0.7em;
    background-color#333;
    border-radius50%;
    topcalc(50% - 0.7em / 2);
    left45%;
}

增加动画鼠标悬停时的动画效果:

.scissors:hover .half {
    animation: cut 2s ease-out;
}

@keyframes cut {
    20%, 60% {
        transformrotate(calc(30deg * var(--direction))) scaleY(var(--direction));
    }

    40%, 80% {
        transformrotate(calc(5deg * var(--direction))) scaleY(var(--direction));
    }
}

最后,别忘了删掉辅助线。

原文出处:https://segmentfault.com/a/1190000016331561

CSS真是神秘~

针对这个题目,你的解决方案又是什么呢?

不妨在下面的留言给出,学习共勉下~

码字不易,走过路过可否点个 在看,点个赞👍先谢谢了!

ε=ε=ε=┏(゜ロ゜;)┛

最后

有疑问的同学 欢迎 评论区讨论,也欢迎大家加入我的前端技术交流群 来讨论。搜索《前端阳光》公众号,回复加群吧!


浏览 30
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报