首页 > 解决方案 > 为什么我的 ::before 元素仅在我使用绝对位置时才显示?

问题描述

我有一个简单的问题,我似乎找不到答案,可能是我没有在谷歌中输入正确的搜索词,但是在试图更好地理解这一点时挠了挠头,我仍然空手而归。

我有一个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伪元素必须绝对定位才能可见?

标签: htmlcssvisibilitypseudo-element

解决方案


您不需要绝对定位。您只需要为 ::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


推荐阅读