Combining Selectors - jpjohnsonjr/learning-notes GitHub Wiki

Methods of Combining

Element with Class Selector

p.big {
  font-size: 20px;
}

Ensure no space in p.big.

Application

<p class="big"> ... </p>
<div class="big"> ... </div>

The 20px rule will apply only to <p> elements and not to the <div> elements in the example above.

Child Selector

Example:

article > p {
  color: blue;
}

Read from right to left. We are targeting in this example every <p> element that is a child of an <article> element. So for example:

<article> ...
  <p> ... </p>
</article>
...
<p> ... </p>
<article> ...
  <div><p> ... </p></div>
</article>

Blue styling will be applied in this example to text within the first <p> tags.

Descendent Selector

For example:

article p {
  color: blue;
}

Targets any element inside of an <article> element, at any level, even if it is not a direct child. Returning to the earlier example:

<article> ...
  <p> ... </p>
</article>
...
<p> ... </p>
<article> ...
  <div><p> ... </p></div>
</article>

This time, both the <p> tags that are the direct child of <article> and the ones that are within <div> will be affected by the styling, but not the ones that are outside of all tags.

Other Ways of Combining

.colored p {
  color: blue;
}

This means "Every p that is inside (at any level) an element with class="colored".

article > .colored {
  color: blue;
}

This means "Every element with class="colored" that is a direct child of article element.

Not covered in the course:

  • Adjacent sibling selector (selector + selector)
  • General sibling selector (selector ~ selector)
⚠️ **GitHub.com Fallback** ⚠️