CSS Combinators

Combined selectors are used to select an HTML element with the help of multiple selectors.

CSS Select All Specific Elements inside Another Specific Element

CSS Code
<!DOCTYPE html>
<html>
<head>
    <style>
        div p {text-align: right; color: seagreen; font-weight: bold;}
    </style>
</head>
<body>

    <div>
        <p>This is Para one, inside DIV</p>
        <p>This is Para two, inside DIV</p>
    </div>
    <p>This is Para one, outside DIV</p>
    
</body>
</html>
Output

This is Para one, inside DIV

This is Para two, inside DIV

This is Para one, outside DIV

Note - Selecting all specific elements inside another element, is called as Descendant selector in CSS.

CSS Select All Elements that are Immediate Child of Another Element

CSS Code
<!DOCTYPE html>
<html>
<head>
    <style>
        body > p {color: seagreen; font-weight: bold;}
    </style>
</head>
<body>

    <div>
        <p>This is Para one, inside DIV</p>
    </div>
    <p>This is Para one, outside DIV</p>
    <p>This is Para two, immediate child of BODY</p>
    
</body>
</html>
Output

This is Para one, inside DIV

This is Para one, outside DIV

This is Para two, immediate child of BODY

Note - Selecting an HTML element that is an immediate child of another HTML element, is known as Child selector.

The syntax of child selector in CSS, is:

elementParent > elementChild {declarations}

CSS Select Particular Element Immediate After Another Element

CSS Code
<!DOCTYPE html>
<html>
<head>
    <style>
        div + p {color: yellowgreen; font-style: italic;}
    </style>
</head>
<body>

    <div>
        <p>This is Para one, inside DIV</p>
    </div>
    <p>This is Para one, immediate after DIV</p>
    <p>This is Para two, after DIV</p>
    
</body>
</html>
Output

This is Para one, inside DIV

This is Para one, immediate after DIV

This is Para two, after DIV

Note - This type of selecting an HTML element, comes under the category of Adjacent Sibling Selector. The character used in this selector is +

CSS Select All Specific Elements Immediate After Another Element

CSS Code
<!DOCTYPE html>
<html>
<head>
    <style>
        div ~ p {color: rebeccapurple; font-style: oblique;}
    </style>
</head>
<body>

    <div>
        <p>This is Para one, inside first DIV</p>
    </div>
    <h2>The General Sibling Selector (~)</h2>
    <p>This is Para one, after first DIV</p>
    <p>This is Para two, after first DIV</p>
    <div>
        <p>This is Para one, inside second DIV</p>
    </div>
    <p>This is Para one, after second DIV</p>
    
</body>
</html>
Output

This is Para one, inside first DIV

The General Sibling Selector (~)

This is Para one, after first DIV

This is Para two, after first DIV

This is Para one, inside second DIV

This is Para one, after second DIV

Note - This type of selector is known as general sibling selector in CSS.

List of Other selectors in CSS:

CSS Online Test


« Previous Tutorial Next Tutorial »