How does the css rule work through the use between selectors: space, ‘+’, ‘>’ or ‘~’ ?

How work CSS rule for two selectors, if we use one of signs: spaces, ‘+’, ‘>’ or ‘~’? I explain it in the following section this post.  We start with first example HTML code :

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" /> 
	<title>My Super Website</title>
	<style>  
	div {
			width:400px; height:300px;
			background-color:lightblue;
         }
	article {
			width:270px; height:120px;
			background-color:lightgreen;
            }
	div p {
	         color:red;
	        }          
	</style>
</head>
<body>

<div>
	<h1>Header</h1>	
	<p>It is first p element in div element</p>
	<p>It is second p element in div element</p>
	<article><p>It is first p element in article element</p>
             <p>It is second p element in article element</p>
       </article> 
	<p>It is third p element in div after article element</p>
</div> 
<p>It is first p element after div element in body element</p>
<p>It is second p element after div element in body element</p>
</body>
</html>

If you run this code you see:

In this example above, we add rule with two selectors separated by space. In this case second selector is descendant. So it doesn’t have to be a child. Look at the code:

div p { color:red; }  

In this examples p elements as child of div and p elements as child of article element  inside div element were formated as red. We can say that all paragraphs into div element are red, because all p tags are descendants of div.

The second example contains the rule consisting of selector div and selector p separated by a sign > .

 div > p { color:blue; }   

In the result we see that p elements into article wasn’t be formated. Why? Because after > sign selector have to be a child of first given selector in the rule. Here p in article element isn’t a child of div element but only a descedent, therefore p in article wasn’t formated.

Ok. But what will happen if after first selector will be plus sign? Do you ready to check it? Let’s go to the third example.

div + p { color:orange; }  

You see first selector and second selector and between them sign ‘+’. Second selector denote a sibling element of first element. However, it denotes only first sister element therefore only first p element places after div element was formated, second p element placed after div element wasn’t formated. Look at the result below.
If you would like to format all p sibling elements placed after div, you have to use in the CSS rule  other sign between these two selectors: div and p. Look at this sign:

 div ~ p { color:fuchsia; }   

And look at the result:

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.