css adjacent sibling selector code example

Example 1: css select all siblings after element

/*To match to any sibling element after the selector on the left,
  use the tilde symbol '~'. This is called the general sibling combinator. */

h1 ~ p {
  color: black;
}

Example 2: adjacent sibling selector

/*The adjacent sibling combinator (+) separates two 
selectors and matches the second element only if 
it immediately follows the first element, and
both are children of the same parent element.*/

li:first-of-type + li {
  color: red;
}

<ul>
  <li>One</li> // The sibling 
  <li>Two</li> // This adjacent sibling will be red
  <li>Three</li>
</ul>

Example 3: css select descendant with class

Select an element with the ID "id" and the class "class":
#id.class {
}
example:
<div>
  <strong id="id" class="class">
      Foobar
  </strong>
  <strong class="class">
      Foobar
  </strong>
</div>
=> Will select the first <strong> element

Select all elements with the class "class",
which are decendents of a element with an ID of "id":
#id .class {
}
example:
<div id="id">
	<strong class="class">Foobar</strong>
</div>
=> Will select the <strong> element

Example 4: css selector for sibling element

/* Paragraphs that come immediately after any image */
img + p {
  font-weight: bold;
}

Tags:

Css Example