What’s the difference between css selectors? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What’s the difference between css selectors?

I have mostly put a space as I was selecting elements Ex header h1 { styles } But recently seen it done this way Header > h1 { style } What’s the difference and what’s the more professional way to select elements more specifically Thanks for your help!

24th Jan 2019, 12:19 PM
John Wick
9 Answers
+ 2
And for the other question, Assume we have an html file with these content. ... <h1>Main heading</h1> <h1> Another</h1> <header> <h1>Header heading</h1> <h1> bla</h1> <div><h1>This wont work</h1></div> </header> ... And we are going to style the h1 h1 { color : red; /*Now all h1 are red*/ } header > h1 { color: blue /*now all h1 inside headers(directly) are blue. Note we are referring to elements which are directly under header. So h1 inside div will still remain red.*/ } Play with these content in the code playground so you can have a better understanding.
24th Jan 2019, 2:53 PM
Seniru
Seniru - avatar
+ 2
Space separated selectors are some sort of trick done to an element in relative to the behaviour of another element. Let me make it clear. Assume we have a btn with id b1. And a paragraph called p1. We need to change the color of the paragraph when hovering b1. Fir that we could use that space separated case. b1:hover p1 { color: red; }
24th Jan 2019, 2:47 PM
Seniru
Seniru - avatar
+ 1
👏
31st Mar 2019, 10:26 AM
PINKY💃😄😄
PINKY💃😄😄 - avatar
0
Header > h1 means the h1 children under a parent header. Which means all the h1 s inside headers. And dont use spaces to separate elements. It means a completely different thing. Just use , instead. Both of these are used for different purposes so all are professional according to me
24th Jan 2019, 12:57 PM
Seniru
Seniru - avatar
0
can you explain how the space is different? I understand the comma but been using the space to select the children of the element and its been working for me that way. so if i did header h1 { color: red } would only make h1 in all the header tags to go red and not the rest. from my understanding thats what header > h1 does as well
24th Jan 2019, 1:35 PM
John Wick
0
okay thank you! I think I got it now. so in your example if i did header h1 { color: red; } it would select the h1 inside the div as well correct?
24th Jan 2019, 5:04 PM
John Wick
- 1
The second selector is for direct child. <header> <h1> Header &gt; h1 style </h1> <div> <h1> Header h1 style </h1> </div>
24th Jan 2019, 12:35 PM
PapaBT
PapaBT - avatar
- 1
With space all descendants are selected. With > only direct childs
24th Jan 2019, 2:39 PM
PapaBT
PapaBT - avatar
- 1
👍
24th Jan 2019, 7:49 PM
PapaBT
PapaBT - avatar