美文网首页
CSS - 阴阳图

CSS - 阴阳图

作者: 写代码的海怪 | 来源:发表于2018-10-22 03:55 被阅读33次

简介

今天教大家用CSS属性做一个简单的阴阳图,效果如下


image.png

只需用简单的CSS样式就可以完成这个阴阳图,这个阴阳图就仅仅是一个div

起步

第一步我们先做一个简单的椭圆,在HTML里添加一个div作为阴阳图的容器。

<div id="yin-yang"></div>

然后用 border-radius 画一个椭圆,这里用 height 大小为 width 两倍就可以了,

#yin-yang {
    width: 96px;
    height: 48px;
    border: 1px solid #41B883;
    border-radius: 50%;
}

效果如下


image.png

变大半圆

我们发现这个椭圆和我们想象的圆不一样呀,这里只要将下面的border宽度变大到和height一半就可以啦

#yin-yang {
    width: 96px;
    height: 48px;
    border: 1px solid #41B883;
    border-bottom-width: 48px;
    border-radius: 50%;
}

效果如下


image.png

是不是有点感觉了呢?下面继续画左右两边的小圆

画小圆

这里先说一下伪元素的概念,就像伪类一样, 伪元素添加到选择器,但不是描述特殊状态,它们允许您为元素的某些部分设置样式。这里用到的伪元素是 ::before::after,相当于在div里面添加前面和后面两个元素。

这里要注意:在伪元素要添加content,否则设置宽高都没用的;还有就是要设置position属性,否则还伪元素还是不会显示

#yin-yang {
    position: relative;
    width: 96px;
    height: 48px;
    border: 1px solid #41B883;
    border-bottom-width: 48px;
    border-radius: 50%;
}

#yin-yang::before {
    content: '';
    position: absolute;
    width: 12px;
    height: 12px;
    background: red;
}

这样我们就将伪元素显示出来了,现在对这个伪元素加些别的样式,让他的位置和颜色和阴阳图相符合

效果如下

image.png

美化小圆

  1. 首先确定好位置,这里要注意,不要直接将left设置为半径的四分之一,因为还要考虑到border的所占的长度
  2. 然后就添加border颜色为大圆的下半部分的颜色
  3. 最后将这个伪元素用 border-radius: 50% 变成小圆
#yin-yang {
    position: relative;
    width: 96px;
    height: 48px;
    border: 1px solid #41B883;
    border-bottom-width: 48px;
    border-radius: 50%;
}

#yin-yang::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 12px;
    height: 12px;
    background: white;
    border: 18px solid #41B883;
    border-radius: 50%;
}

效果如下

image.png

和 before 伪元素一样的思路,设置一个 after 伪元素,将上面的属性取一下反,就有右边的小半圆了,所以总的CSS样式如下

#yin-yang {
    position: relative;
    width: 96px;
    height: 48px;
    border: 1px solid #41B883;
    border-bottom-width: 48px;
    border-radius: 50%;
}

#yin-yang::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 12px;
    height: 12px;
    background: white;
    border: 18px solid #41B883;
    border-radius: 50%;
}
#yin-yang::after {
    content: '';
    position: absolute;
    top: 50%;
    right: 0;
    width: 12px;
    height: 12px;
    background: #41B883;
    border: 18px solid white;
    border-radius: 50%;
}

最终的效果如下

image.png

相关文章

网友评论

      本文标题:CSS - 阴阳图

      本文链接:https://www.haomeiwen.com/subject/zbhwzftx.html