如何使用css實現中國結的效果(代碼)

來源:互聯網
上載者:User
這篇文章給大家帶來的內容是關於如何使用css實現中國結的效果(代碼) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

今天跟大家分享一個用 css 畫中國結的教程。
最終效果如下:

首先,我們定義好畫中國結需要的結構:

<div class="knot">    <span class="box"></span>    <span class="box"></span>    <span class="box"></span>    <span class="box"></span></div>

然後開始寫樣式,讓中國結置中顯示:

body {  margin: 0;  padding: 0;  height: 100vh;  display: flex;  align-items: center;  justify-content: center;}

設定裝中國結的容器樣式:

.knot {  box-sizing: border-box;  font-size: 100px;  width: 2em;  height: 1.6em;  background: skyblue;  display: flex;  align-items: center;  justify-content: center;}

我把中國結的基礎樣式拆分成4個長方形,首先來定義長方形的基礎樣式:

.box {  position: absolute;  box-sizing: border-box;  width: 1em;  height: 0.4em;  border: var(--b) solid firebrick;  --b: 0.1em;}

然後我們來調整每一個長方形的樣式,把它們組合成結的基礎樣子:

.knot .box:nth-child(1) {  transform: rotate(45deg) translate(-15%, -38%);  border-radius: 20% 0% 0% 20% / 50% 0 0 50%;}.knot .box:nth-child(2) {  transform: rotate(45deg) translate(15%, 37%);  border-radius: 0% 20% 20% 0% / 0% 50% 50% 0%;}.knot .box:nth-child(3) {  transform: rotate(-45deg) translate(15%, -38%);  border-radius: 0% 20% 20% 0% / 0% 50% 50% 0%;}.knot .box:nth-child(4) {  transform: rotate(-45deg) translate(-15%, 37%);  border-radius: 20% 0% 0% 20% / 50% 0 0 50%;}

最後,我們利用第一個和第二個長方形的虛擬元素來畫出餘下的那兩個小圓圈:

.knot .box:nth-child(1)::after {  box-sizing: border-box;  content: '';  position: absolute;  width: 0.4em;  height: 0.4em;  border: var(--b) solid firebrick;  border-radius: 50% 50% 50% 0%;  top: -0.4em;  right: -0.4em;}.knot .box:nth-child(2)::after {  box-sizing: border-box;  content: '';  position: absolute;  width: 0.4em;  height: 0.4em;  border: var(--b) solid firebrick;  border-radius: 50% 0% 50% 50%;  top: 0.2em;  right: 0.8em;}
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.