首页 > 解决方案 > CSS 选择器:父类匹配子类

问题描述

我有一个看起来像这样的 html 结构:

<ul class = "one">
<li class = "one">one</li>
<li class = "two">two</li>
</ul>



<ul class = "four">
<li class = "three">three</li>
<li class = "four">four</li>
</ul>

我想创建一个 css 选择器,它选择父类和子类匹配的元素(另请参见我的jsfiddle 示例。到目前为止,我对此非常明确:

.one > .one,
.two > .two
.three > .three,
.four > .four
{
  color: red
}

有没有办法不那么明确?像这样的东西:if parent classes match child class

标签: htmlcss

解决方案


你不能用纯 CSS 选择父级,伪“:has”只是草稿,现在任何浏览器都不支持它。https://developer.mozilla.org/en-US/docs/Web/CSS/:has

不过用jquery很容易

$(function() {
  $("li").each(function(index) {
    if ($(this).parent('ul').attr('class') == $(this).attr('class')) {
      $(this).css('color', 'red')
    }

  });
})

jsfiddle在这里


推荐阅读