Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selector Not Working (~)

I am learning CSS and was trying to figure out a way to make the background color of the body change as you hover over the header element on the page. I have tried to use every selector and it just doesn't work! Can anyone help me figure out my problem? Here is my code:

<html>

 <style>


  #header {
   text-align: center;
   position: relative;
  }

  #header:hover ~ .body{
   background-color: blue;
  }

  .body{
   background-color: purple;
  }


 </style>

 <body class="body">

  <div id="header">
   <font size="16">My Header</font>
  </div>

 </body>

</html>
like image 337
Jake Avatar asked Feb 10 '23 00:02

Jake


1 Answers

In the code you have, what you are trying to do, in essence, is select a parent element.

In other words, body is the parent of div#header, and you are trying to select body on hover of its child.

In CSS, there is no way to select the parent of an element. CSS doesn't work that way.

You can read more about this restriction here: Is there a CSS parent selector?

The selector you are trying to use (~) is called a general sibling selector and it matches elements that share the same parent.

Read more about it here: General sibling selectors on MDN.

If you really want to select a parent element you can look into a Javascript / jQuery solution.

For some interesting reading as to why there is no parent selector in CSS, visit: Parent Selectors in CSS on CSS-Tricks.

For a complete list of CSS Selectors, visit: W3C Selectors Level 3.

like image 118
Michael Benjamin Avatar answered Feb 11 '23 14:02

Michael Benjamin