开发者

Do the contextual rules for 'type' selectors also apply for 'class' & 'id' selectors in CSS?

I am new to CSS and facing an issue related to contextual selectors as following:

Q1) What is the effect of creating selectors in the following way:

.test1 .test2{
    background:red;
}

Here test1 and test2 are the class selectors.

I understand that when we use such structure with 'type' selectors then that leads to styling of descendants.

Is this the same thing for the class selectors?

Q2) If yes, then will all the contextual rules (+, >) etc.. for the 'type' selector will also apply for class selectors?

Q3) And will all these rules also be then applicable to the 'id' selectors?

I have seen the use of such structure in the css files of js libraries like ExtJS

.x-border-box .x-reset *{box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;-webkit-box-sizing:border-box}

But I have 开发者_运维百科not been able to locate the exact implication of this structure.

Could any guide at this.

Thanks for any help in advance.


  1. Yes, it is the same thing for class selectors.
  2. Yes, the contextual rules that apply to type selectors will also apply to class selectors.
  3. Yes, they will also be applicable to id selectors.

I have seen the use of such structure in the css files of js libraries like ExtJS

.x-border-box .x-reset *{box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;-webkit-box-sizing:border-box}

But I have not been able to locate the exact implication of this structure.

It means, apply that rule to all child elements of the element with the class x-reset, whose immediate or any further parent has the class x-border-box.


Yes, they work the same. They're all simple selectors.


Q1) What is the effect of creating selectors in the following way:

.test1 .test2{ background:red; }

This will change the background-color of an element with the class of test2 that is nested within the class of test1.

So yes.

Q2) If yes, then will all the contextual rules (+, >) etc.. for the 'type' selector will also apply for class selectors?

Yes, they apply. But there are slight differences.

For instance, the above rule is close to the same as .test1 > .test2. This targets the direct child of .test1, whereas the first rule (with just the classes) would target any .test2 descendent of a .test1, no matter who nested.

Q3) And will all these rules also be then applicable to the 'id' selectors?

Yes, id and class work the same way, expect that id targets a specific, unique element and class can be applied to multiple elements.


You can just mix and match. So something like this:

#header h1.main a

Means; any a-element, that is a descendant of a h1 element with a classname that is 'main', that again is a descendant of any element with a ID 'header'. Note that you could just replace #header with *#header (although I would not do that)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜