+ 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!
9 ответов
+ 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.
+ 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;
}
+ 1
👏
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
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
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?
- 1
The second selector is for direct child.
<header>
<h1> Header > h1 style </h1>
<div>
<h1> Header h1 style </h1>
</div>
- 1
With space all descendants are selected.
With > only direct childs
- 1
👍