css 如何绘制正方形?

前言

如何绘制正方形的问题呢,在这里我先只写一种方式,后续补齐。

正文

写正方形有一个很特殊的地方就在于我们在写html的时候,宽是一定固定的,因为不可能溢出去,但是高就不固定了,因为可能要滑动。

问题就回到了,知道了宽,如何设定高的问题了。

padding 方式

原理:padding的宽度的百分比是根据width来确定的。

.container{
  width: 200px;
  background: yellow;
}
.container::before
{
  content:"";
  padding-top:100%;
  display: block;
}

这样通过befor把元素撑开。

但是呢,里面的元素已经被占用了,那么我们需要书写不是container而是这样。

.container{
  width: 200px;
  background: yellow;
  position: relative;
}
.container::before
{
  content:"";
  padding-top:100%;
  display: block;
}
.ele{
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
}

html:

<div class="container">
<div class="ele">
  dsda
</div>
</div>