CSS中的黄金比例
黄金比例,也称为黄金数、黄金比例,甚至神圣比例,是指两个数字之间的一种特殊比例,其约等于1.618。它通常用希腊字母“phi”表示。令人着迷的是,这个比例与斐波那契数列有着密切的联系——斐波那契数列是一系列数字,每个数字都是前两个数字之和。斐波那契数列以0、1开头,然后依次为:1、2、3、5、8、13、21等等。随着序列的推进,每个数字与前一个数字之间的比例越来越接近1.618,即phi。这种独特的比例在自然、艺术和建筑中随处可见,既具有数学上的奇思妙想,又具有视觉上的美感!
在本教程中,我们将使用一些网格声明和一些额外的技巧在 CSS 中重新创建黄金比例图。
让我们开始吧!
我们将使用斐波那契数列的这一部分:
1, 1, 2, 3, 5, 8, 13, 21
<ol>
这是 8 位数字,所以我们的标记将由8 个元素组成<li>
。
在 CSS 网格中,我们将创建一个画布,其尺寸由宽度的最后两位数字13 + 21 = 34
和21
高度的最大数字之和得出:
ol {
all: unset;
display: grid;
grid-template-columns: repeat(34, 1fr);
grid-template-rows: repeat(21, 1fr);
list-style: none;
}
目前还看不到太多内容,但如果我们启用 Dev Tool 的Grid Inspector,我们就可以看到网格:
接下来,我们将为元素添加一些通用样式<li>
:
li {
aspect-ratio: 1 / 1;
background: var(--bg);
grid-area: var(--ga);
}
仍然没有什么可看的,所以让我们用一些内容填充--bg
( background-color
) 和--ga
( ) 变量:grid-area
&:nth-of-type(1) {
--bg: #e47a2c;
--ga: 1 / 1 / 22 / 22;
}
&:nth-of-type(2) {
--bg: #baccc0 ;
--ga: 1 / 22 / 23 / 35;
}
&:nth-of-type(3) {
--bg: #6c958f;
--ga: 14 / 27 / 22 / 35;
}
&:nth-of-type(4) {
--bg: #40363f;
--ga: 17 / 22 / 22 / 27;
}
&:nth-of-type(5) {
--bg: #d7a26c;
--ga: 14 / 22 / 17 / 25;
}
&:nth-of-type(6) {
--bg: #ae4935;
--ga: 14 / 25 / 17 / 27;
}
&:nth-of-type(7) {
--bg: #e47a2c;
--ga: 16 / 26 / 17 / 27;
}
&:nth-of-type(8) {
--bg: #f7e6d4;
--ga: 16 / 25 / 17 / 26;
}
现在,我们得到了这个:
太棒了!发生了什么?我们使用自定义属性赋予每个矩形<li>
各自的大小。然后,我们用来在网格中放置矩形并调整其大小。以下是简写:background-color
--bg
grid-area
grid-area
row-start / col-start / row-end / col-end
现在,如何创建螺旋效果?虽然 CSS 不能直接绘制螺旋,但我们可以通过::after
在每个 元素上添加圆圈作为伪元素来模拟螺旋效果<li>
:
li {
/* as before */
overflow: hidden;
position: relative;
&::after {
aspect-ratio: 1 / 1;
background-color: rgba(255, 255, 255, .3);
border-radius: 50%;
content: '';
display: block;
inset: 0;
position: absolute;
}
}
这给了我们:
还没有完全达到这个效果,但如果我们将圆圈的大小加倍并稍微平移一下,它就会开始看起来更好:
&::after {
/* as before */
scale: 2;
translate: var(--tl);
}
但是,除非我们更新--tl
每个的 (translate) 属性,否则不会有太大的变化<li>
:
&:nth-of-type(1) {
--tl: 50% 50%;
}
&:nth-of-type(2) {
--tl: -50% 50%;
}
/* and so on for the rest */
现在我们得到这个:
这里发生了什么?
我们创建了一个大小为其元素两倍的圆圈,然后使用平移将圆圈向不同方向移动,使其呈现出连续螺旋的外观。通过调整每个元素的平移,圆圈彼此“流动”,模仿螺旋。
最后,由于我们添加了overflow: hidden
元素<li>
,当圆圈溢出容器时,它们会被“切断”,从而给我们一种完美螺旋的错觉!
这是 CodePen 中的最终结果:
文章来源:https://dev.to/madsstoumann/the-golden-ratio-in-css-53d0