为什么我的 ::before 元素仅在我使用绝对位置时显示?

Why does my ::before element only display if I use position absolute?

我有一个简单的问题,我似乎无法找到答案,可能是我没有在 Google 中输入正确的搜索词,但在挠头之后为了更好地理解这一点,我仍然空手而归。

我有一个 span 元素,它有一个 ::before 伪元素,没什么特别的,只是一个简单的圆圈。但是,我注意到我必须绝对定位伪元素才能使其可见。我发现这很奇怪,并且不确定我是否只是没有完全理解这种性质的伪元素,或者我是否错误地实现了这个想法。

无论哪种方式,这里都有一个使用和不使用绝对定位的示例。

html,
body {
  margin: 0;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

span {
  margin-bottom: 15px;
}

.no-absolute::before,
.absolute::before {
  content: '';
  width: 10px;
  height: 10px;
  margin-right: 5px;
  border-radius: 50%;
  background-color: #f33;
  cursor: pointer;
}

.absolute {
  position: relative;
}

.absolute::before {
  position: absolute;
  top: 4px;
  left: -15px;
}
<span class="no-absolute">No Absolute</span>
<span class="absolute">Absolute</span>

为什么我的 ::before 伪元素必须绝对定位才能可见?

您不需要绝对定位。你只需要为 ::before 伪元素

设置 display 属性

html,
body {
  margin: 0;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

span {
  margin-bottom: 15px;
}

.no-absolute::before{
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 5px;
  border-radius: 50%;
  background-color: #f33;
  cursor: pointer;
}
<span class="no-absolute">No Absolute</span

您的 pseudo 元素需要显示 属性。我添加了 display: block.

html,
body {
  margin: 0;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

span {
  margin-bottom: 15px;
  position: relative;
}

.no-absolute::before,
.absolute::before {
  content: '';
  width: 10px;
  height: 10px;
  margin-right: 5px;
  border-radius: 50%;
  background-color: #f33;
  cursor: pointer;
  display: block;
}

.absolute {
  position: relative;
}

.absolute::before {
  position: absolute;
  top: 4px;
  left: -15px;
}
<span class="no-absolute">No Absolute</span>
<span class="absolute">Absolute</span>

答案是:你需要display来给出伪元素的大小/形状(blockinline-block)。 inline 元素 接受宽度/高度。

或者你可以用 padding 来给它大小/形状,但是 displaywidth / height 最有意义。

span {
  margin-bottom: 15px;
  position: relative;
}

.no-absolute::before,
.absolute::before {
display: block;
  content: '';
  width: 10px;
  height: 10px;
  margin-right: 5px;
  border-radius: 50%;
  background-color: #f33;
  cursor: pointer;
}
<span class="absolute">Absolute</span>