如何在CSS3中将:nth-​​of-type选择器与:before选择器一起使用?

时间:2019-01-22 15:00:19

标签: css3 css-selectors

我正在从事Drupal 8项目。我有一个侧边栏,其中有一个无序列表,以动态方式插入DOM。我一直在尝试通过CSS3伪类:before插入一些SVG,并且有效。但是,我需要为该列表上的不同锚标记插入不同的SVG。因此,我尝试这样做:

ul {
 li {
  a {
    &:nth-of-type(1):before {
     //Code goes here
    }
    &:nth-of-type(2):before {
     //Code goes here
    }
    &:nth-of-type(3):before {
     //Code goes here
    }
  }
 }
}

任何想法如何做到这一点?预先感谢

HTML标记:

<ul>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Menu Link 1</a>
    </li>
    <li>
    <a href="" data-drupal-link-system-path="<front>">Menu Link 2</a>
                                        <ul>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Submenu-sidebar 1</a>
    </li>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Submenu-sidebar 2</a>
    </li>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Submenu-sidebar 3</a>
    </li>
    </ul>

    </li>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Menu Link 3</a>
    </li>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Menu Link 4</a>
    </li>
    <li>
        <a href="" data-drupal-link-system-path="<front>">Menu Link 5</a>
    </li>
</ul>

到目前为止我尝试过的:

ul {
     border: none;
     -webkit-box-shadow: 1px 0px 9px 0 rgba(0,0,0,0.75);
     -moz-box-shadow: 1px 0px 9px 0 rgba(0,0,0,0.75);
      box-shadow: 1px 0px 9px 0 rgba(0,0,0,0.75);
      list-style: none;
      padding: 0;
      margin: 0;
      width: rem(280px);
      li {
          a {
            background-color: $white;
            color: $greyish-brown;
            display: block;
            padding: rem(20px) rem(35px);

            &:hover {
               background-color: $blue-green;
               color: $white;
            }
            }
            a:nth-of-type(1):before {
              @extend %svg-sidebar-decorations;
              background-image: url("../images/picto-info-sant.svg");
            }
             a:nth-of-type(2):before {
                @extend %svg-sidebar-decorations;
                background-image: url("../images/picto-infosocial.svg");

             }
             a:nth-of-type(2):before {
                @extend %svg-sidebar-decorations;
                background-image: url("../images/picto-infosocial.svg");
             }
            }

    %svg-sidebar-decorations {
    content: '';
    display: inline-block;
    width: rem(14px);
    height: rem(16px);
    margin-top: rem(3);
    margin-right: rem(10px);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
}

1 个答案:

答案 0 :(得分:1)

使用nth-child(n)代替nth-of-type(n),并将这些选择器移至li级别。

您的SCSS(?)可能看起来像这样:

ul {
  li {
    &:nth-child(1) a:before {
      //Code goes here
    }
    &:nth-child(2) a:before {
      //Code goes here
    }
    &:nth-child(3) a:before {
      //Code goes here
    }
  }
}

Example CodePen