纯CSS绘制椭圆与平行四边形

2,061 阅读1分钟

这是我参与8月更文挑战的第15天,活动详情查看:8月更文挑战

border-radius

我们都知道的一个常用的CSS属性: border-raduis,通过它可以设置DOM元素的4个角的的半圆。例如:

image.png

源代码:

<!DOCTYPE html>
<body>
    <div class="circle-box">
        border-radius: 50%;
    </div>
</body>
<style>
    .circle-box {
        width: 200px;
        height: 200px;
        border-radius: 50%;
        background-color: lightblue;
        font-weight: bold;
        color: black;

        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
</style>
</html>

border-radius的官方文档链接:developer.mozilla.org/zh-CN/docs/…

其含义为:

允许你设置元素的外边框圆角。当使用一个半径时确定一个圆形,当使用两个半径时确定一个椭圆。这个(椭)圆与边框的交集形成圆角效果。

那么,如何使用两个半径呢? border-radius是个简写属性,是四个属性 border-top-left-radiusborder-top-right-radiusborder-bottom-right-radius,和 border-bottom-left-radius 的简写。

举例来说,如何书写其中的一个属性呢?比如border-top-left-radius

两个半径:先横后竖

border-top-left-radius官网链接为:developer.mozilla.org/zh-CN/docs/…

其定义上图示非常清楚地写明了是如何定义两个半径的,如下图所示:

border-top-left-radius: horizontal vertical // 即 横向,竖向

image.png

比如我们只定义左上角:

width: 200px;
height: 200px;
border-top-left-radius: 100px 200px;

效果图如下所示:

image.png

左上角是“先横后竖”,那么其他三个角呢?答案是相同的,均是“先横后竖”,我们可以记忆为“先水平,后垂直”。

那么如何利用这个特性绘制椭圆呢?很简单,设置一个宽高比为2/1或者1/2的图形,然后设置border-radius: 50%即可。

image.png