Nesting selectors - possible?

2019-02-23 16:47发布

问题:

Suppose I have a div with a bunch of stuff inside:

<div id="Product">
 <ul id="List"></ul>
 <div class="Component"></div>
 <input type=... />
 ...
</div>

Now, I want to style various things, but only when inside of the #Product div. Generally, I would do:

#Product #List {}
#Product .Component {}
#Product input {}

But, can I do something like this instead?

#Product {
    #List {}
    .Component {}
    input {}
}

回答1:

Nesting CSS selectors is not possible with standard CSS, but there are other tools like SASS, LESS, and XCSS which allow you to write rules in the way you're describing.

These tools generally "compile" into real CSS which handles converting the nested selector syntax into real CSS rules.



回答2:

Yes, but not in regular CSS. You can use Sass! http://sass-lang.com/



回答3:

No, you can't nest rules in CSS yet. There are CSS preprocessors available which allow cool features like nesting, variables, etc.

Check out LESS.