仅使用填充创建方形伪元素



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

只有当右/左填充是顶部/底部填充的 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;,它将是一个正方形。

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> 

请参阅迈克尔的答案,了解您问题中的原因。

我只想指出,大多数时候,标题的答案是使用百分比填充相对于事物宽度的事实。是的,宽度,而不是高度。即您可以添加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>

生成的内容从父级继承字体大小及其行高。

您可以重置字体大小以隐藏两者或仅隐藏行高。

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> 

最新更新