开发者

usage of spaces in CSS files

This one has to be the most basic question but it's not clear in my mind, so I'd like to ask it:

Say you have some basic HTML like this:

<div class="a">
    <p class="b">something</p>
 开发者_如何学Go   <img class="b">
    <p class="c">something</p>
</div>

How can you select the first <p> element using CSS?

The reason why I'm puzzled that up till now I believed that CSS can work by both specifying type and class, but it seems I cannot do it. So I can have something like: div p or div .b or .a p or .a .bbut not div .a p .b as I was believing and as how every browser tool names the elements (like div.a p.b)

Is all this issue because of the space between the class and the type?


Is all this issue because of the space between the class and the type?

Yes, a space is a descendent selector.

a.b means "An element of type a and class b".

a .b means a *.b means "An element of any type and class b that is a descendent of an element of type a.


Basically yes, it is because of the space. So selecting the paragraph with class b can be achieved by:

.a .b {
/* Rules */
}

Or to be more specific:

div.a p.b {
    /* Rules */
}

Whereas the second rule only selects any p element with the class b which is inside a div with the class a. The first one selects any element with class b inside any element with class a.


Try this:

.a .b { color:red; }

Or even this (though it may not work in older browsers):

.a p:first-child { color:red; }

If you're going to use the elements name (like img.className) you cannot have a space in between the element's name and it's class or id name. Spaces are used as delimiters, and act sort of like a directory tree would: .a .b p { color:red; } is synonymous with saying color all paragraph's red that are in .b's which are in .a's.


These should all work...

div :first-child             //first child of a div

p:first-child                //first p

div p:first-child            //first p child of a div

.a p:first-child             //first p child of class .a

div p.b                      //p's with class .b as decedents of div

.a p.b                       //p's with class .b as decedents of class .a

No space, as in p.b will reference all P with class .b

With a space, as in p .b will reference decedents of P with class .b


you need to do

div.a p.b 

What you are doing with

div .a p .b

is: fetch the class b elementes, see which one are inside a p, from those which one are inside a element of class a, and of those which one are inside a div.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜