我的 css ::after 仅适用于最后一个元素

My css ::after apply only on the last element

我想为我的 div 添加边框底部渐变,在网上查看后我找到了一个解决方案:

.element {
  height: 55px;
  max-width: 400px;
  background-color: #454A4D;
  margin-top: 20px;
}
.element:after {
   content: "";
   background: -webkit-linear-gradient(left, #343738 0%, #e07051 100%);
   display: block;
   height: 4px;
   width: 400px;
   position: absolute;
   bottom: 0;
}

"element" 是我的 div,

的 class

我得到的正是我想要的风格,但它只适用于最后一个 div 和 class .element !这给了这个:

有什么线索吗?

将位置 属性 设置为相对于您的 .element 选择器。

是的,菜单项(元素 1、元素 2 和元素 3)未定位。他们是static。包含它们的元素有一个 positionabsolutefixedrelative),这导致 after 将该元素作为参考来放置它们自己.

在元素上设置相对位置可以解决您的问题:

.element {
    position: relative;
}
.element:after {
    content: "";
    background: -webkit-linear-gradient(left, #343738 0%, #e07051 100%);
    display: block;
    height: 4px;
    width: 400px;
    position: absolute;
    bottom: 0;
}