使用css选择器lastchild和:在angular2之后一起使用

时间:2017-04-24 10:54:43

标签: html css css3 sass css-selectors

HTML:

<h2 class="title-main">
     <span class="title-inside">A</span>
     <span class="title-inside">B</span>
     <span class="title-inside">C</span>
     <span class="title-inside">D</span>
     <span class="title-inside">E</span>
     <span class="title-outside">F</span>
     <span class="title-outside">G</span>
</h2>

CSS:

:host/deep/.title-main {
    display: flex;
    margin-bottom: 0;

    .title-inside {
        &:after {
            content : '-';
        }
    }
}

我得到像这样的输出

A-B-C-D-E-F G

我不想要 - 为最后一个孩子。我想要像这样的输出

A-B-C-D-E F G

我尝试了很多选择。例如。我试过的其中一个

title-inside:last-child ::after {
           content: ''
    }

但这不起作用。有谁可以帮助我

2 个答案:

答案 0 :(得分:2)

:not:nth-last-of-type()

一起使用

.title-main {
  display: flex;
  margin-bottom: 0;
}

.title-inside:not(:nth-last-of-type(3))::after {
  content: '-';
}
<h2 class="title-main">
  <span class="title-inside">A</span>
  <span class="title-inside">B</span>
  <span class="title-inside">C</span>
  <span class="title-inside">D</span>
  <span class="title-inside">E</span>
  <span class="title-outside">F</span>
  <span class="title-outside">G</span>
</h2>

以下是SASS version

:host/deep/.title-main {
    display: flex;
    margin-bottom: 0;

    .title-inside {
        &:not(:nth-last-of-type(3)){
           &::after{
            content : '-';
           }
        }
    }
}

答案 1 :(得分:2)

由于:nth-*last-child选择器使用实际的元素类型而不是类名,我认为最好使用类选择器。

通过使用::before伪而不是兄弟选择器+,每个类有多少项无关紧要,它始终是正确的。

.title-main {
  display: flex;
  margin-bottom: 0;
}

.title-main  .title-inside + .title-inside::before {
  content: '-';
}
<h2 class="title-main">
     <span class="title-inside">A</span>
     <span class="title-inside">B</span>
     <span class="title-inside">C</span>
     <span class="title-inside">D</span>
     <span class="title-inside">E</span>
     <span class="title-outside">F</span>
     <span class="title-outside">G</span>
</h2>


<h2 class="title-main">
     <span class="title-inside">A</span>
     <span class="title-inside">B</span>
     <span class="title-inside">C</span>
     <span class="title-outside">D</span>
     <span class="title-outside">E</span>
     <span class="title-outside">F</span>
     <span class="title-outside">G</span>
</h2>

SASS

:host/deep/.title-main {
    display: flex;
    margin-bottom: 0;

    .title-inside {
      &+.title-inside {
        &::before{
          content : '-';
        }
      }
    }
}