Html 在菜单中为 Sass 应用最后一个子选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19932687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:15:40  来源:igfitidea点击:

Applying last child selector for Sass in menu

htmlcsssasscompass-sass

提问by user1781367

Working on a navigation using Sass. I'm trying to use :last-child selector to apply different link color(red) for the last menu link but no success. Can anyone show me how to achieve from the following Sass code? below is the code I have so far. Any advice would be greatly appreciated!

使用 Sass 进行导航。我正在尝试使用 :last-child 选择器为最后一个菜单链接应用不同的链接颜色(红色),但没有成功。谁能告诉我如何从以下 Sass 代码中实现?下面是我到目前为止的代码。任何建议将不胜感激!

HTML

HTML

<ul class="menu">
   <li>
       My Navigation
   </li>
   <li>
       <a href="#">First Link</a>
   </li>
   <li>
       <a href="#">Second Link</a>
   </li>
   <li>
       <a href="#">Third Link</a>
  </li>
</ul>

Sass

萨斯

.menu {
    @include inline-list;
    font-size: 13px;


    &, a {
        color: black;
        text-decoration: none;

    }
    > * + * {
        margin-left: .5em;

        + *:before {
            content: ">";
            margin-right: .5em;
        }
    }

    & a ul li:last-child {
        color: red;
        font-weight: bold;
    }
}

回答by Shauna

Your CSS is off. Your last line is targeting the last child of an li that's a child of an anchor tag. Also, you don't need to use &when targeting children of the selector you're nesting in.

您的 CSS 已关闭。您的最后一行针对作为锚标记子代的 li 的最后一个子代。此外,&在定位嵌套选择器的子级时,您不需要使用。

So, change your last-child selection to:

因此,将您的最后一个孩子选择更改为:

li:last-child a

and it should work. You need to target the link in order to override your original link declaration.

它应该工作。您需要定位链接以覆盖原始链接声明。

回答by Christoph

The following selector works:

以下选择器有效:

& li:last-child a

Check it out in this demo fiddle

在这个演示小提琴中查看

You don't need the & though, since it is automatically prepended:

您不需要 & 虽然,因为它会自动添加:

li:last-child a

In every case you should avoid *selectors, they have horrible performance. In almost every case, there is a better selector you could replace this with. In your case,

在任何情况下你都应该避免*选择器,它们的性能很差。几乎在所有情况下,都有一个更好的选择器可以替换它。在你的情况下,

> li + li {
/*and*/
    &:before {
    }

work too.

也工作。

&, a

also makes not much sense, since &simply resolves to the parent selector. Unless you intended this, to write DRY code, putting those two declarations in the parent block and omitting the &would be the better option.

也没有多大意义,因为&只是解析到父选择器。除非您打算这样做,否则要编写 DRY 代码,将这两个声明放在父块中并省略&将是更好的选择。