CSS 选择器最后一个可见的 child

标签 css

<分区>

CSS 中是否有一种方法可以在不知道使元素不可见的类的情况下将 CSS 规则应用于最后一个可见的子元素?

例子:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li style="display: none">Item 5</li>
<ul>

<style>
  ul > li {
    border: 1px solid black;
  }

  // Remove right border from last visible child
  // This does not work of course, but this is what I am looking for
  ul > li:last-child:not([style="display: none"]) {
    border-right: none;
  }
</style>

明确一点:我正在寻找基于规则的选择器,而不是基于 CSS 而非 Javascript 的类。但是这个答案A CSS selector to get last visible div例如不起作用。这里的问题是 :last-child 和 :not 不能合并。 :last-child([style="display: block"]) 也不起作用(当 li 有 dispay: block 时),因为它查看样式属性而不是 CSS 规则。

bootstrap 中的示例(注意:hidden-md 是一个示例,它也可以是其他使用 display:none 的类):

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li class="hidden-md">Item 5</li>
<ul>

最佳答案

用 CSS 是不可能的,但是你可以用 jQuery 做到这一点。 Try this clumsy code .

jQuery:

 $('li').not(':hidden').last().addClass("red");

HTML:

<ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li class="hideme">Item 4</li>    
</ul>

CSS:

.hideme {
    display:none;
}

.red {
    color: red;
}

jQuery(以前的解决方案):

var $items = $($("li").get().reverse());

$items.each(function() {

    if ($(this).css("display") != "none") {
        $(this).addClass("red");
        return false;
    }

});

关于CSS 选择器最后一个可见的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22527858/

上一篇:javascript - 悬停子项时突出显示父项

下一篇:css - li 标签内的 Firefox 奇怪行为右对齐跨度

相关文章:

javascript - CSS在Chrome中申请代码,在Firefox和IE中申请不到?

html - 填充Font-awesome图标的透明度

html - 如何让这些 Bootstrap 列相互堆叠?

html - 使 UL 更改其 parent 大小的正确方法是什么?

css - Sass @extend 兄弟选择器引用父选择器(&符号)

css - 完全显示背景图像

javascript - 如何延迟每个元素的 jQuery Waypoint 以产生惊人的效果?

css - Bootstrap 3 : why do my <div>s stack from 992 px width onwards when using "col-sm-6"

jquery - 是否可以将图像放在 html 中的 <hr> 标记上方?

javascript - jQuery Calculate (window).innerHeight() 减去 vh