0

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?

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.