sibling selector code example
Example 1: general sibling selector
/* The general sibling combinator (~) separates
two selectors and matches the second element
only if it follows the first element
(though not necessarily immediately),
and both are children of the same parent element. */
/* Paragraphs that are siblings of and
subsequent to any image will be red */
img ~ p {
color: red;
}
<img src="myimg.png"/>
<p>This will be red!</p>
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 sibling
/*
Adjecent Sibling Selector
-------------------------
example: Select all <p> tags that immediatly follows after <div> tag
*/
div + p {
background-color: yellow;
}
/*
General Sibling Selector
-------------------------
example: Select all <p> tags that has a sibling with a <div> tag
*/
div ~ p {
background-color: yellow;
}
Example 4: descendent selector in css
The descendant combinator — typically represented by a single space ( )
character — combines two selectors such that elements matched by the second
selector are selected if they have an ancestor
(parent, parent's parent, parent's parent's parent, etc)
element matching the first selector.
example:
h1 ul {
border : 1px solid #f1f1f1;
}
Explanation: This above CSS code snippet will select all the 'ul' (unordered list)
tags which are preceeded by an 'h1' (header tag).
/*the best way to understand is to practice by implemetation.
Create a html file with lots of h1 and ul elements to understand by
implementing CSS on them*/
Example 5: sibling selector css
/*General Sibling*/
/*The general sibling selector selects all elements that are siblings of a specified element.
The following example selects all <p> elements that are siblings of <div> elements: */
/*<div></div>
<p></p>*/
div ~ p{
}
/*Adjacent Sibling*/
/*The adjacent sibling selector is used to select an element that is directly after another specific element.
Sibling elements must have the same parent element, and "adjacent" means "immediately following".
The following example selects the first <p> element that are placed immediately after <div> elements*/
/*<div><p></p></div>
*/
div + p{
}
Example 6: css selector for sibling element
/* Paragraphs that come immediately after any image */
img + p {
font-weight: bold;
}