lostvita / blog

60 stars 47 forks source link

css画出响应式正方形 #29

Open lostvita opened 3 years ago

lostvita commented 3 years ago

如何使用纯css,来画出跟随窗口变化的正方形?

image 今天看到了vmin和vmax属性,很有意思,感觉在某一些场景下很好用!

  1. 先来介绍一下vm和vh vm是viewport width的缩写,顾名思义,就是视窗的宽度,100vw就是100%的视窗宽度;同理,100vh就是100%的视窗高度。

  2. vmin和vmax是什么? 看名词就能理解得到,vmin表示vw和vh中的较小者,vmax表示vw和vh中的较大者。如上图片示例中,视窗的宽度大于视窗高度,那么vmin = vh,vmax = vw。 如此,纯css来实现一个正方形就很简单了:

    .box { width: 20vmin; height: 20vmin }

    image

这样就能实现一个边宽总是等于视窗中最小长度的边的20%。

还有别的方式吗?

padding-top/padding-bottom:当padding的单位为%时,它的值是相对于自身元素的width的。

In CSS, all four margin: and padding: percentages are relative to the width ...even though that may seem nonsensical. That's just the way the CSS spec is, there's nothing you can do about it. 可以用以下的方式:

.box { width: 20%; padding-top: 20%; }

image

🤔emmm......any else ?