CSS Tutorial 7: Sibling Selectors

Share

[Lesson 6] <<[Contents]>>[Lesson 8]

We have learned about the child and descendant selectors in CSS. In this lesson, we shall learn about another type of selectors. The selectors resemble members of a family, so they are called sibling selector.

There are two types of sibling selectors in CSS, the adjacent sibling selector, and the general sibling selector.

7.1 Adjacent Sibling Selector

An adjacent sibling selector only selects an element that is directly after another specific element.  It uses the plus sign + to join the two elements together. The syntax is

element1+element2{ }

It means the selector targets the first element2 after any element1.

Example 7.1

<!Doctype html>

<html>

<head>

<title> Sibling Selector in CSS</title>
<style type=”text/css”>
p+h2{ text-decoration:underline;color:red}
</style>
</head>
<body>
<p>We have learned about child and descendent selectors in previous lesson. In this lesson, we shall learn about another type of selector. It resembles members of a family, so it is called sibling selector.

There are two types of sibling selectors, they are <h2>adjacent sibling selector </h2> and <h2>general sibling selector</h2></p>
</body>
</html>

 

The Output

We have learned about the child and descendant selectors in the previous lesson. In this lesson, we shall examine another type of selector which also resembles members of a family, it is called sibling selector. There are two types of sibling selectors, they are

adjacent sibling selector

and

general sibling selector

Notice that only the first h2 element was affected by p CSS styling, but the second h2 element is not affected.

7.2 General Sibling Selector

A general sibling selector selects an element which may be directly or not directly after another specific element.  It uses the tilde sign ~ to join the two elements together. The syntax is

element1~element2{ }

Example 7.2

<!Doctype html>

<html>

<head>

<title> Sibling Selector in CSS</title>
<style type=”text/css”>
p~h2{ text-decoration:underline;color:red}
</style>
</head>
<body>
<p>We have learned about <h2>child and descendent selectors </h2>in previous lesson. In this lesson, we shall learn about another type of selector which also resembles members of a family, it is called sibling selector.

There are two types of <h2>sibling selectors</h2>, they are <h2>adjacent sibling selector</h2> and <h2>general sibling selector</h2></p>
</body>
</html>

 

The Output

We have learned about

child and descendent selectors

in the previous lesson. In this lesson, we shall study another type of selector which also resembles members of a family, it is called sibling selector.

There are two types of

sibling selectors

, they are

adjacent sibling selector

, they are

general sibling selector

Notice that only the first and all subsequent h2 elements were affected by p css styling.

[Lesson 6] <<[Contents]>>[Lesson 8]

Share