2016-06-08 100 views
1

我需要将CSS样式添加到父列表中。在主ul中但不嵌套的目标列表项ul

我有一个家长ul和孩子。我想申请颜色水果蔬菜但不苹果香蕉

我想使用CSS选择器来做到这一点。

ul:root>li { 
 
    color: red; 
 
}
<ul> 
 
    <li>Fruits 
 
    <ul> 
 
     <li>Apple</li> 
 
     <li>Banana</li> 
 
     <li>Orange</li> 
 
    </ul> 
 
    </li> 
 

 
    <li>Vegetables</li> 
 
    <li>Flowers</li> 
 
</ul>

+1

您将应用于这些元素的准确风格是什么? 'color'是一个继承的属性,所以一旦你将它分配给外部'li',它里面的'ul'和'li'将继承这个颜色。你不得不超越它。 – Harry

回答

2

你可以一类简单地添加到父ul然后用嫡系选择的目标只有那些li项目。

这是肯定会改变颜色苹果橙色但你可以重置子ul指定的颜色。

这是您的更新演示。

.parent-list > li { 
 
    color: red; 
 
} 
 
.parent-list > li ul { 
 
    color: initial; 
 
}
<ul class="parent-list"> 
 
    <li>Fruits 
 
    <ul> 
 
     <li>Apple</li> 
 
     <li>Banana</li> 
 
     <li>Orange</li> 
 
    </ul> 
 
    </li> 
 

 
    <li>Vegetables</li> 
 
    <li>Flowers</li> 
 
</ul>

1

使用这样的...

<ul> 
 
    <li>Fruits 
 
    <ul> 
 
     <li>Apple</li> 
 
     <li>Banana</li> 
 
     <li>Orange</li> 
 
    </ul> 
 
    </li> 
 

 
    <li>Vegetables</li> 
 
    <li>Flowers</li> 
 
</ul> 
 
\t \t \t \t \t \t \t 
 

 
<style> 
 
ul li{ 
 
    color: red; 
 
} 
 
ul li li{ 
 
    color: black; 
 
} 
 
</style>

1

ul > li {    /* select list items that are children of a ul */ 
 
    color: red; 
 
} 
 

 
ul ul li {    /* select list items that are descendants of a ul, itself... */ 
 
    color: black;   /* ...a descendant of another ul */ 
 
}
<ul> 
 
    <li>Fruits 
 
    <ul> 
 
     <li>Apple</li> 
 
     <li>Banana</li> 
 
     <li>Orange</li> 
 
    </ul> 
 
    </li> 
 
    <li>Vegetables</li> 
 
    <li>Flowers</li> 
 
</ul>

-2
<style> 
ul li { 
    color: red; 
} 

ul ul li { 
    color: black; 
} 
</ul> 

</style> 


<ul> 
    <li>Fruits 
    <ul> 
     <li>Apple</li> 
     <li>Banana</li> 
     <li>Orange</li> 
    </ul> 
    </li> 

    <li>Vegetables</li> 
    <li>Flowers</li>