草庐IT

html - CSS :last-of-type not working in combination with :not

coder 2023-08-03 原文

我有一些与提供的代码段行为方式相同的东西。 I've got a list of items, that when one is selected, I want that one to be displayed at the top of the list, which I can easily do with flex ordering.一次只能选择一个。但是由于每个列表元素都有边框,所以最后一个元素不应该有边框。在大多数情况下,只需使用 li:last-of-type 就可以正常工作,除非它是最后一个被选中的列表项。

我已经尝试了几个选择器,它们应该选择没有给定类的无序列表中的最后一个列表项,但是 last-of-type 选择器似乎不是行为得体。

如果代码中不清楚,我指的选择器是 .selection li:not(.selected):last-of-type。问题是列表底部的双边框。它应该是来自无序列表元素的单个边框。

.selection ul {
  display: flex;
  flex-direction: column;
  border: .15rem solid #666;
}

.selection li {
  order: 2;
  border-bottom: .15rem dashed #666;
}

.selection li.selected {
  order: 1;
}

/** This selector should work in my mind, but it doesn't **/
.selection li:not(.selected):last-of-type {
  border-bottom: none;
}

/** Non-important styles to put it into context **/
ul { list-style: none; padding: 0; width: 25%; margin: 2rem auto; }
li { padding: 1rem 2rem; background-color: #ebebeb; }
li:hover { background-color: #ccc; }
a { color: inherit; text-decoration: none; }
<div class="selection">
  <ul>
    <li><a href="">1</a></li>
    <li><a href="">2</a></li>
    <li class="selected">3</li>
  </ul>
</div>

我还创建了这个 Codepen snippet来证明问题。

我觉得这是 :last-of-type 选择器的问题,也许我用错了,但在我看来,上面的选择器应该可以工作。

任何帮助或深入了解如何解决此问题,或以其他方式选择元素,或深入了解为什么这不起作用,我们将不胜感激。

最佳答案

考虑这种替代方法:

  • 完全摆脱 :not 选择器
  • 仅在左侧、右侧和顶部为 ul 设置边框
  • 仅将底部边框应用于 li

ul {
    display: flex;
    flex-direction: column;
    border-top: .15rem solid #666;
    border-left: .15rem solid #666;
    border-right: .15rem solid #666;
}

li { border-bottom: .15rem solid #666; }

Revised Codepen


这就是您的选择器不起作用的原因:

.selection li:not(.selected):last-of-type { border-bottom: none; }

在我看来,你是说你想匹配最后一个 li 元素,只要它没有 selected 类。

但这不是 last-of-type 的工作方式。如果 li 是兄弟,选择器将匹配它,而不管 class选择器匹配 DOM 元素。这意味着即使您将 display: none 应用于 li,选择器仍会匹配它。 p>

6.6.5.9. :last-of-type pseudo-class

The :last-of-type pseudo-class represents an element that is the last sibling of its type in the list of children of its parent element.

source: https://drafts.csswg.org/selectors-3/#last-of-type-pseudo

更多详情:How to get nth-child selector to skip hidden divs

关于html - CSS :last-of-type not working in combination with :not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35461242/

有关html - CSS :last-of-type not working in combination with :not的更多相关文章

随机推荐