SmartCodingTips

CSS Combinators

CSS combinators are used to define relationships between selectors. They allow you to style elements based on their relationship in the HTML structure.

1. Descendant Selector (space)

Selects all elements that are inside another element.


div p {
    color: green;
}
            

Styles all <p> elements that are inside any <div>, regardless of depth.

2. Child Selector (>)

Selects all direct child elements.


ul > li {
    list-style-type: square;
}
            

Only applies styles to <li> elements that are direct children of <ul>.

3. Adjacent Sibling Selector (+)

Selects the element that is immediately next to another element.


h1 + p {
    font-style: italic;
}
            

Targets a <p> that comes right after an <h1> element.

4. General Sibling Selector (~)

Selects all sibling elements that appear after a specified element.


h1 ~ p {
    color: darkgray;
}
            

Applies to all <p> elements that follow an <h1> within the same parent.

Conclusion

Combinators help you write more specific and powerful CSS rules by defining relationships between elements. Use them to target elements based on their position or structure in the HTML document.