Tech Junkie Blog - Real World Tutorials, Happy Coding!: CSS: Combinators

Monday, September 23, 2019

CSS: Combinators

Combinators in CSS is term used to define a style that combines more than one selectors together.

For example let's say you have the following markup

        <div id="combinator-div"><h1>I'll be back.</h1></div>
        <h1>Combinator me</h1>

Let's say you only want to apply the styles for the <h1> tag that's inside the combinator-div, you can use a combinator style which is a combination of the div id and the h1 tag as combination to style a very specific element on the page.  The style would look like the following

#combinator-div h1 {font-family: sans-serif; font-weight: bold; color: green;}

If you run the page with the code then you would get the following output











As you can see only the I'll be back <h1> is styled, the other <h1> is just not cool enough to get styled.



There are more combinators that you can do that's more specific, they are the following:

  • Adjacent Sibling + 
    • Applies the styles to the adjacent tag only the matches the combinator
    • Let's say you have the following style defined as your combinator
      • h3 + p {font-family: sans-serif; font-weight: bold; color: green;}
      • And the following HTML markup 

            <p>I am green</p>
            <h3>I am green</h3>
            <p>I am green</p>
            <p>I am green</p>
            <h3>I am green</h3>
            <p>I am green</p>

The output is 
  • General Sibling ~
    • The general sibling is as the name implies it's not as strict, as long as there's an <h3> as the parent all the <p> tags will be applied the styles
    • Let's you have the following style 
      • h3 ~ p {font-family: sans-serif; font-weight: bold; color: green;}
    • With the following HTML
            <p>I am green</p>
            <h3>I am green</h3>
            <p>I am green</p>
            <p>I am green</p>
            <p>I am green</p>

The output is

  • Child >
    • Applies style to only the direct child of the first element for example if you have the following style
      • div > p {font-family: sans-serif; font-weight: bold; color: green;}
    • With the following HTML
        <div>
            <p>I am green</p>
            <article>
                <p>I am green</p>
            </article>
            <p>I am green</p>
        </div>

The output is

As you can see the <p> in the <article> tag is not green
  • Descendent 
    • which is just white separator is the ones being used the most, this combinator will seek out all the occurrences of the second element and apply the style so if we have the following style div p {font-family: sans-serif; font-weight: bold; color: green;} with the same HTML as the one above.  We would have the following output














Everything is green, including the <p> element inside the <article> element.

No comments:

Post a Comment

Search This Blog