如何防止CSS继承? [英] How do I prevent CSS inheritance?

查看:136
本文介绍了如何防止CSS继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在侧边栏中有一个使用嵌套列表(< ul>和< li>标签)的分层导航菜单。我使用的已经有列表项目样式的预制主题,但我想改变顶级项目的样式,但不适用于子项目。有没有简单的方法来应用样式到顶级列表项标签没有那些样式级联到其子列表项?我明白我可以明确地添加覆盖样式到子项,但我真的想避免重复所有的样式代码,如果有一个简单的方法,只是说应用这些样式到这个类,不要级联他们到任何孩子元素。
这是我使用的html:

I have a hierarchical navigation menu in my sidebar that uses nested lists (<ul> and <li> tags). I am using a pre-made theme which already has styles for list items, but I want to alter the style for the top-level items but NOT have it apply to the sub-items. Is there an easy way to apply styles to the top-level list item tag WITHOUT having those styles cascade down to its children list items? I understand that I can explicitly add overriding styles to the sub-items but I'd really like to avoid having to duplicate all of that style code if there is an easy way to just say "apply these styles to this class and DO NOT cascade them down to any children elements". Here is the html I'm using:

<ul id="sidebar">
  <li class="top-level-nav">
    <span>HEADING 1</span>
    <ul>
      <li>sub-heading A</li>
      <li>sub-heading B</li>
    </ul>
  </li>
  <li class="top-level-nav">
    <span>HEADING 2</span>
    <ul>
      <li>sub-heading A</li>
      <li>sub-heading B</li>
    </ul>
  </li>
</ul>

所以css已经有#sidebar ul和#sidebar ul li我想为#sidebar .top-level-nav添加额外的样式,不会级联到它的子子孙。
有没有办法做到这一点,或者我需要重新安排所有的样式,所以#sidebar ul的样式现在特定于某些类。

So the css has styles for "#sidebar ul" and "#sidebar ul li" already, but I'd like to add additional styles to "#sidebar .top-level-nav" that do NOT cascade down to its subchildren. Is there any way to do this simply or do I need to rearrange all of the styles so the styles that were on "#sidebar ul" are now specific to certain classes.

推荐答案

由于还没有父选择器(或 Shaun Inman 称呼他们,合格的选择器),因此您将必须对子列表项应用样式以覆盖父列表项上的样式。

As of yet there are no parent selectors (or as Shaun Inman calls them, qualified selectors), so you will have to apply styles to the child list items to override the styles on the parent list items.

级联是级联样式表的整体点,因此是名称。

Cascading is sort of the whole point of Cascading Style Sheets, hence the name.

这篇关于如何防止CSS继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆