Use a space or greater than sign > in CSS selector? [duplicate]

No they are completely different, using > selects a child element whereas using a space will select a nested element at any level.

For example…

Using /space in the selector…

<div class="welcome">
    <section>
        <div>This will be selected</div>
    </section>
    <div>This will be selected as well</div>
</div>

So here, the selector having space will target the div at any nested level of the parent element.

Demo (Using /space)

.welcome div {
    font-size: 20px;
    color: #f00;
}

Using >

<div class="welcome">
    <section>
        <div>This won't be selected</div>
    </section>
    <div>This will be selected</div>
</div>

Whereas here, the selector will target your div which is a child of the element having .welcome but it won’t select the div which is nested inside section tag as it is a grandchild (but not a child) of the outer div.

Demo 2 (Using >)

.welcome > div {
    font-size: 20px;
    color: #f00;
}

From MDN : (For )

The combinator (that’s meant to represent a space, or more
properly one or more whitespace characters) combines two selectors
such that the combined selector matches only those elements matching
the second selector for which there is an ancestor element matching
the first selector. Descendant selectors are similar to child
selectors, but they do not require that the relationship between
matched elements be strictly parent-child.

From MDN : (For >)

The > combinator separates two selectors and matches only those
elements matched by the second selector that are direct children of
elements matched by the first. By contrast, when two selectors are
combined with the descendant selector, the combined selector
expression matches those elements matched by the second selector for
which there exists an ancestor element matched by the first selector,
regardless of the number of “hops” up the DOM.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)