首页 > 解决方案 > 使用 :before 和 :after 创建的 CSS 元素不显示

问题描述

我尝试显示这样的 html 元素: here

这是一个底部带有箭头的正方形,我使用这种样式创建了它:

.square {
  min-width: 60px;
  height: 60px;
  margin-left: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #1db911;
  border-radius: 15px;
  font-size: 14px;
  color: #ffffff;
}

.square:after,
.square:before {
  bottom: 30%;
  left: 31%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  display: block;
}

.square:after {
  border-color: rgba(238, 238, 238, 0);
  border-top-color: #1db911;
  border-width: 10px;
  margin-left: -10px;
  display: block;
}
.square:before {
  border-color: rgba(204, 204, 204, 0);
  border-top-color: #1db911;
  border-width: 10px;
  margin-left: -10px;
  display: block;
}

但有一个问题。当我水平滚动时,三角形停留在: 这里 ,这是我的父元素: 这里 可以水平滚动。我也尝试使用position: relativefor squareclass,但它有问题。它没有在正方形上显示三角形。像这样: 这里(我将三角形涂成黑色以更好地显示)这是我在这个州的风格

.square {
  min-width: 60px;
  height: 60px;
  margin-left: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #1db911;
  border-radius: 15px;
  font-size: 14px;
  color: #ffffff;
  position: relative;
}

.square:after,
.square:before {
  bottom: -22%;
  left: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  display: block;
}

.square:after {
  border-color: rgba(238, 238, 238, 0);
  border-top-color: black;
  border-width: 10px;
  margin-left: -10px;
  display: block;
}

.square:before {
  border-color: rgba(204, 204, 204, 0);
  border-top-color: #1db911;
  border-width: 10px;
  margin-left: -10px;
  display: block;
}
<div class="square">
  <span>sample</span>
</div>

谢谢!

标签: htmlcsscss-selectorspseudo-element

解决方案


除了使用底部,您可以使用top:100%,如果您希望正方形仅与内容一样宽,您可以使用inline-flex

.square {
  min-width: 60px;
  height: 60px;
  margin-left: 5px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  background-color: #1db911;
  border-radius: 15px;
  font-size: 14px;
  color: #ffffff;
  position: relative;
}

.square:after,
.square:before {
  top: 100%;
  left: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  display: block;
}

.square:after {
  border-color: rgba(238, 238, 238, 0);
  border-top-color: #1DB911;
  border-width: 10px;
  margin-left: -10px;
  display: block;
}

.square-container:before {
  border-color: rgba(204, 204, 204, 0);
  border-top-color: #1db911;
  border-width: 10px;
  margin-left: -10px;
  display: block;
}
<div class="square">
  <span>sample</span>
</div>


推荐阅读