溢出:隐藏不适用于伪元素

overflow: hidden doesn't work on a pseudo element

我有一个红色方块 (div) 和一个橙色条作为伪元素 (before)。
我想隐藏父方块外的橙色条的一部分,所以我在父方块上使用了 overflow: hidden;,但它不起作用。

.square {
  width: 3.5em;
  height: 3.5em;
  
  background-color: red;
  overflow: hidden;
}

.square::before {
  content: "";
  position: absolute;
  transform: translate(2em);
  width: 4.95em;
  height: .65em;
  background-color: orange;
}
<div class="square"></div>

您需要将 position: relative 设置为 .square

.square {
  width: 3.5em;
  height: 3.5em;
  position: relative; /* Added */
  background-color: red;
  overflow: hidden;
}

.square::before {
  content: "";
  position: absolute;
  transform: translate(2em);
  width: 4.95em;
  height: .65em;
  background-color: orange;
}
<div class="square"></div>

问题

伪元素当前相对于根元素定位。

解决方案

您需要使其相对于 .square,而不是将 position: relative; 添加到 .square

.square {
  width: 3.5em;
  height: 3.5em;
  
  background-color: red;
  overflow: hidden;
Position:relative;
}

.square::before {
  content: "";
  position: absolute;
  transform: translate(2em);
  width: 4.95em;
  height: .65em;
  background-color: orange;
}
<div class="square"></div>