General Sibling Selectors in CSS


The CSS general sibling selector is used to select all elements that follow the first element such that both are children of the same parent.

Syntax

The syntax for CSS general sibling selector is as follows

element ~ element {
   /*declarations*/
}

The following examples illustrate CSS general sibling selector −

Example 1

In this example, we have <ul> tags. We also have a <p> tag between two <ul> tags −

<ul>
   <li><img src="https://www.tutorialspoint.com/images/pl-sql.png"></li>
</ul>
<p>We provide learning tutorials, quizzes and video tutorials.</p>
<ul>
   <li>Tutorials on databases and programming languages.</li>
   <li>Quizzes to check knowledge of databases and languages.</li>
   <li>Video Tutorials to easily understand the technologies.</li>
</ul>

For the <ul> tag after the <p> tag, we have set styles using the General Sibling Selectors concept −

p ~ ul {
   box-shadow: inset 4px 0 3px lime;
}

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <style>
      * {
         float: left;
         padding-left: 14px;
         list-style: none;
      }
      p ~ ul {
         box-shadow: inset 4px 0 3px lime;
      }
   </style>
</head>
<body>
   <h1>Demo Heading</h1>
   <ul>
      <li><img src="https://www.tutorialspoint.com/images/pl-sql.png"></li>
   </ul>
   <p>We provide learning tutorials, quizzes and video tutorials.</p>
   <ul>
      <li>Tutorials on databases and programming languages.</li>
      <li>Quizzes to check knowledge of databases and languages.</li>
      <li>Video Tutorials to easily understand the technologies.</li>
   </ul>
   <ul>
      <li><img src="https://www.tutorialspoint.com/images/mongodb.png"></li>
      <li><img src="https://www.tutorialspoint.com/images/db2.png"></li>
      <li><img src="https://www.tutorialspoint.com/images/sql.png"></li>
   </ul>
</body>
</html>

Example 2

In this example, we have an <img> tag between two <p> tags −

<p>This is demo text.</p>
<img src="https://www.tutorialspoint.com/big_data_analytics/images/big-data-analytics-mini-logo.jpg">
<p>Learn Big Data Analytics at no cost.</p>

For the <p> tag after the <ul> tag, we have changed the background color using the General Sibling Selectors concept −

img ~ p {
   background-color: burlywood;
}

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <style>
      * {
         float: left;
         padding: 10px;
         list-style: none;
      }
      img ~ p {
         background-color: burlywood;
      }
   </style>
</head>
<body>
   <p>This is demo text.</p>
   <img src="https://www.tutorialspoint.com/big_data_analytics/images/big-data-analytics-mini-logo.jpg">
   <p>Learn Big Data Analytics at no cost.</p>
</body>
</html>

Updated on: 02-Nov-2023

897 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements