Make :after element 只有在它后面有另一个元素时

Make :after element only if there is another element after it

我只想在后面有其他元素的情况下添加元素。 到目前为止,这是我的代码:

<table id='table_1'>
   <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
 </tr> 
</table>

是否可以在 A 和 B 之后有 :after 而不是 C?

我的 CSS

#table_1 td:after{
content: "";
background: black;
border: 1px solid black;
position: relative;
margin-left: 10px;
}

您可以使用 td:last-child 到 select 任何作为其父元素的最后一个子元素的 td 元素,然后隐藏其 :after 伪元素:

#table_1 td:last-child:after {
    display:none;
}

演示:

#table_1 td:after {
    content:"";
    background: black;
    border: 1px solid black;
    position: relative;
    margin-left: 10px;
}
#table_1 td:last-child:after {
    display:none;
}
<table id='table_1'>
    <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
    </tr>
</table>

最简单的 方法是使用 not(:last-child):

#table_1 td:not(:last-child):after{
    content: "";
    background: black;
    border: 1px solid black;
    position: relative;
    margin-left: 10px;
}

Working exmaple

这样你就只有一个选择器,你不需要覆盖你的代码。

您可以将 :before+ 结合使用以获得旧版浏览器支持

Adjacent sibling selector

#table_1 td {
  position: relative;
}
#table_1 td + td:before {
  content: "";
  position: absolute;
  background: black;
  border: 1px solid black;
  position: relative;
  margin-left: 10px;
  margin-right: 10px;
}
<table id='table_1'>
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
</table>