CSS Combinators Demo

Introduction to CSS combinators

In CSS, combinators are special characters that connect multiple selectors together. They define the relationship between those selectors, allowing you to target elements with even greater precision. Imagine them as the glue that builds intricate family trees for your web page elements.

  • The Child Selector (>):This combinator selects elements directly nested within another. Think styling "li > a" to target only links directly inside list items.
  • The Adjacent Sibling Selector (+):This one grabs elements immediately following another. Want to highlight every heading followed by a paragraph? Use "h2 + p" and watch the magic unfold.
  • The General Sibling Selector (~):This combinator targets any element sharing the same parent, no matter the order. Style all list item bullets with "li ~ li::marker" and see them transform in unison.
  • The Descendant Selector (space):This one reaches across generations, selecting any element that's a descendant of another – children, grandchildren, and so on. Use ".featured p" to style all paragraphs nested within elements having the "featured" class.

HTML Code for demo on Combinators

 <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="test.css">
    <title>Document</title>
  </head>
  <body>
    <div>
    <nav>
      <ul>
        <li><a href="test.css">Home</a></li>
        <li><a href="test.css">Register</a></li>
        <li><a href="test.css">About</a></li>
      </ul>
    </nav>
    <h1>This is heading1</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit ipsum ipsa omnis? Eum incidunt alias rerum nihil impedit autem, sed magni consequatur enim iusto quo delectus possimus maxime atque veritatis.</p>
    <h1>This is heading2</h1>
    <h1>This is heading3</h1>
  </div>
  </body>
  </html> 

CSS File for demo code on Combinators

 /* descendent selectors */
  nav ul li a
  {
      color:red;
  }
  
  nav ul li{
      list-style-type: none;
      padding: 10px;
      float:left;
  }
  
  nav ul li a:hover
  {
      background-color: aqua;
  }
  
  /*child selector */
  div>p
  {
      color:blue;
  }
  
  /*adjacent sibling selector*/
  p+h1
  {
      color:brown;
  }
  /*General sibling selector*/
  p~h1
  {
      color:brown;
  } 

Output

image of a webpage showing use of combinators