What do the following CSS selectors mean?

  1. div, p
  2. div p
  3. div ~ p
  4. div + p
  5. div > p

The meaning of the given list of selectors goes as follows:

  • div, p: This selector implies selecting all div elements and all p elements.

Consider an example below:

<h1>Heading 1</h1>
<div>
	Division 1
	<p> paragraph 1</p> <!-- Will be selected -->
</div>
<p> paragraph 2</p> 
<p> paragraph 3</p> 
<div>
	Division 2
</div>
<span>Span 1</span>

Here, all the div elements and the p elements would be selected by the browser irrespective of their parents or where they are placed. The remaining tags like h1 and span are ignored.

  • div p : This selector tells to select all p elements that are inside div elements. Consider an example below:
<h1>Heading 1</h1>
<div>
    Division 1
    <p> paragraph 1</p> <!-- Will be selected -->
    <div>
        <p> Inner Div Paragraph </p> <!-- Will be selected -->
    </div>
</div>
<p> paragraph 2</p>
<p> paragraph 3</p>
<div>
    Division 2
</div>
<span>Span 1</span>

Here, <p> paragraph 1</p> and <p> Inner Div Paragraph </p> would be selected by the browser and the properties are applied. The rest of the paragraph tags are not selected.

  • div ~ p : This selector tells to select all p elements that have div elements preceeding anywhere. Consider an example,
<h1>Heading 1</h1>
<div>
   Division 1
   <p> paragraph 1</p>
</div>
<p> paragraph 2</p> <!-- Will be selected -->
<p> paragraph 3</p> <!-- Will be selected -->
<div>
   Division 2
</div>
<span>Span 1</span>

Here, paragraph 2 and paragraph 3 elements would be selected as marked in the code above.

  • div + p : This selector says to select all p elements placed immediately after the div element. Consider an example in this case:
<h1>Heading 1</h1>
<div>
	Division 1
	<p> paragraph 1</p>
</div>
<p> paragraph 2</p> <!-- Will be selected -->
<p> paragraph 3</p> 
<div>
	Division 2
</div>
<span>Span 1</span>

In this case, we have paragraph 2 element immediately after the div tag. Hence, only that element will be selected.

  • div > p : This selector says to select all p elements which has div as an immediate parent. In the same example below:
<h1>Heading 1</h1>
<div>
	Division 1
	<p> paragraph 1</p> <!-- Will be selected -->
</div>
<p> paragraph 2</p> 
<p> paragraph 3</p> 
<div>
	Division 2
</div>
<span>Span 1</span>

Only <p> paragraph 1</p> will be selected in this case because it has immediate div as the parent.