【问题标题】:Using css selector lastchild and :after together in angular2在angular2中一起使用css选择器lastchild和:after
【发布时间】:2017-05-05 09:24:27
【问题描述】:

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: ''
    }

但这不起作用。谁能帮帮我

【问题讨论】:

  • 我也试过这样。那是行不通的

标签: html css sass css-selectors


【解决方案1】:

使用: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 : '-';
           }
        }
    }
}

【讨论】:

  • 我试过你的方法。但是其他孩子也没有炒作
  • 我刚刚更新了SASS版本,忘记了&amp;::after再看一遍
  • 感谢您的回答。但我不知道,在我的情况下这是行不通的
  • 我已经更新了我的 html。请你看一下。我希望将该样式应用于 title-inside 的最后一个子项。 @dippas
  • 是的,它奏效了。我用过:nth-​​child(5)。我试过 urs 也很好用。非常感谢
【解决方案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 : '-';
        }
      }
    }
}

【讨论】:

  • 我不想要 E 之后的连字符
  • @Priya 用可能有帮助的解释更新了我的答案
猜你喜欢
  • 2010-12-27
  • 2022-01-22
  • 2011-08-17
  • 2021-07-31
  • 2016-12-02
  • 1970-01-01
  • 2011-07-23
相关资源
最近更新 更多