Problem with Using ">" in CSS

Hi everybody! I’m starting code from the beginning. When I’m studying code samples to finish my project (5 projects as required) I have difficulty to understand about when using ‘>’ as below in CSS:
nav > ul { : use ‘>’
.logo > img { : use ‘>’
#hero > h2 { : use ‘>’

nav li { : No use ‘>’ between ‘nav’ and ‘li’
#hero input: No use ‘>’ between attribute hero and input tag
#features .icon: No use ‘>’

I show above from this sample at here: https://codepen.io/freeCodeCamp/pen/RKRbwL
So everybody can explain to me when can use ‘>’ and not.
Thank you very much!

@thanhgt86 In CSS > is used to select unique children. For example:
You want to give width 100px to all div tags from section tags which are in body. It would be like:

body > section > div {
  width: 100px;
}

When you write like that, only the divs from section elements will have width of 100px not every divs.

Hope This Help

1 Like

@AndrewAung11: thank you for your answer! But I see some case to select unique children not use ‘>’, like I show above:

nav li { : No use ‘>’ between ‘nav’ and ‘li’
#hero input: No use ‘>’ between attribute hero and input tag
#features .icon: No use ‘>’ between attribute features and class icon

So can you explain to me more in what case will no use ‘>’ to select unique children?

@thanhgt86 I think there is no different between them. But > might be used as barrier not to select (for example in .class1 .class2) .class1 and .class2 . Because here take a look:



When selecting .class1 element’s child .class2, like this .class1 class2, the css might understand it as selecting those two classes. So we can avoid it by using >.
Images are taken from:
https://www.w3schools.com/cssref/css_selectors.asp

This explanation is better: Problem with Using ">" in CSS - #5 by jsdisco

1 Like

You’re not selecting unique children but direct children.

Take this HTML as an example:

<div>
    <span>
        <span></span>
   </span>
</div>

The selector div span would target both spans in the above example.

The selector div > span would target only the outer span.

2 Likes

@AndrewAung11 @jsdisco : Thank you for your support, now I understand the matter. Happy coding!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.