Combinators

  Combinators



In CSS, combinators define the relationship between two or more selectors. Here’s how they work:


  • Descendant Combinator (parent descendant)

Selects elements that are descendants (children, grandchildren, etc.) of a specified parent.

parent descendant {

    /* Styles applied to all <descendant> elements within <parent> */

}

Example:

<div class="parent">
    <p class="descendant">Text</p>
</div>

.parent .descendant { /* targets <p> inside <div> */}

  • Child Combinator (parent > child)
Selects elements that are direct children of a specified parent.

parent > child {

    /* Styles applied to direct children only */

}

 Example:

<div class="parent">
    <p class="child">Text</p>
</div>

.parent > .child { /* targets <p> directly inside <div> */}


  • Adjacent Sibling Combinator (sibling + self)
Selects an element (self) that directly follows a sibling.

sibling + self {
    /* Styles applied to <self> directly after <sibling> */
}

Example:

<h2 class="sibling">Heading</h2>
<p class="self">Text</p>

.sibling + .self { /* targets <p> immediately after <h2> */}


  • General Sibling Combinator (sibling ~ self)
Selects all elements (self) that share the same parent and follow a sibling.

sibling ~ self {
    /* Styles applied to all <self> elements after <sibling> */
}

Example:

<h2 class="sibling">Heading</h2>
<p class="self">Paragraph 1</p>
<p class="self">Paragraph 2</p>


.sibling ~ .self { /* targets both <p> elements following <h2> */}




Output will appear here...

Post a Comment

0 Comments