hyperknot
hyperknot

Reputation: 13976

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>
    <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?

Upvotes: 0

Views: 845

Answers (5)

wdm
wdm

Reputation: 7189

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

Upvotes: 1

theabraham
theabraham

Reputation: 16370

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.

Upvotes: 1

Daff
Daff

Reputation: 44215

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.

Upvotes: 1

Quentin
Quentin

Reputation: 943586

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.

Upvotes: 4

fceruti
fceruti

Reputation: 2445

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.

Upvotes: 0

Related Questions