仅使用填充制作方形伪元素

Make a Square Pseudo Element Only using Padding

为什么四边填充相等的伪元素不是正方形?

当 right/left 填充是 top/bottom 填充的 1.5 倍时,我只能实现方形伪元素。

见下面的代码。

button{
  width: 200px;
  height: 100px;
  background: gray;
  border:none;
  font-size:16px;
}

.icon::before {
    // position: relative;
    padding: 20px;
    content: "";
    background: black; 
}

.icon2::before {
    padding: 20px 30px;
    content: "";
    background: black; 
}
<p>Pseudo element: padding on all sides is 20px.</p>
<button class="icon">
  Click Me
</button> 

<p>Pseudo element: padding on top/bottom is 20px, padding on left/right is 30px.</p>
<button class="icon2">
  Click Me
</button> 

因为默认情况下它被视为内联元素,font-size 会影响元素的大小。更改 font-size: 0; 或添加 display: block; 并匹配 height/width,它将成为一个正方形。

button{
  width: 200px;
  height: 100px;
  background: gray;
  border:none;
  font-size:16px;
}

.icon::before {
    // position: relative;
    padding: 20px;
    content: "";
    background: black; 
    display: block;
    width: 0;
    height: 0;
}

.icon2::before {
    padding: 20px;
    content: "";
    background: black; 
    font-size: 0;
}
<p>Pseudo element: padding on all sides is 20px.</p>
<button class="icon">
  Click Me
</button> 

<p>Pseudo element: padding on top/bottom is 20px, padding on left/right is 30px.</p>
<button class="icon2">
  Click Me
</button> 

生成的内容从父级继承 font-size 及其 line-height。

您可以重置 font-size 以隐藏两者或仅隐藏 line-height。

button{
  width: 200px;
  height: 100px;
  background: gray;
  border:none;
  font-size:16px;
}

.icon::before {
    font-size:0;/* remove space used from inserted text and line-height*/
    padding: 10%;/* 10% of 200px width is 20px */
    vertical-align:middle;/* can be usefull;*/
    margin-right:0.25rem;/* keep away from next phrasing content */
    content: "";
    background: black; 
}

.icon2::before {
    padding: 20px 30px;
    content: "";
    background: black; 
}
<p>Pseudo element: padding on all sides is 20px.</p>
<button class="icon">
  Click Me
</button> 

<p>Pseudo element: padding on top/bottom is 20px, padding on left/right is 30px.</p>
<button class="icon2">
  Click Me
</button> 

请参阅 Michael 的回答,了解您问题中原因的答案。

我只想指出,大多数时候 title 的答案是使用百分比填充是相对于事物宽度的事实。是的,宽度,不是高度。 IE。您可以添加 padding-bottom: 100% 来实现正方形。或者使 62.5% 达到 16:9 比率,例如用于视频。

.square {
  width: 100px;
}

.square::before {
  display: block;
  content: '';
  padding-bottom: 100%;
  border: 1px solid red;
}
<div class="square"></div>