CSS Selectors

CSS element name selector

CSS id Selector

The CSS rule below will be applied to the HTML element with id="para1":
	#para1 {
  		text-align: center;
  		color: red;
	}
		
		<p id="para1">Hello World!</p>
		<p>This paragraph is not affected by the style.</p>
		

CSS class Selector

In the example below, all HTML elements with class="center" will be red and center-aligned: :
		.center {
  			text-align: center;
  			color: red;
			}
			
		<h1 class="center">Red and center-aligned heading</h1>
		<p class="center">Red and center-aligned paragraph.</p>
			

CSS Grouping Selector

In this example we have grouped the selectors from the code above:
h1, h2, p {
  text-align: center;
  color: red;
}
		

multiple Selector

Parents, children, siblings

first child selector

Example:

✅ Works (First Child)
		<div>
    			 <p>This paragraph will be red.</p>
   			 <p>This paragraph will NOT be red.</p>
		</div>		
		
Explanation: The first <p> inside the <div> is the first child, so it turns red.


❌Won't Work (Not First Child)
			<div>
    				<h2>Heading</h2>
    				<p>This paragraph will NOT be red.</p>
    				<p>Neither will this one.</p>
			</div>
		

Explanation: The <h2> is the first child of <div>, so the first <p> is not affected by p:first-child.

nth child selector

Example:

✅ Works (Second Child)
		<div>
			 <p>First paragraph (not red).</p>
    			 <p>Second paragraph (red).</p>
   			 <p>Third paragraph (not red).</p>
		</div>		
		
Explanation: The second <p> is the second child of <div>, so it turns red.


❌Won't Work (Not Second Child)
		<div>
			 <p>First paragraph (not red).</p>
    			 <h1>Heading (not red).</h1>
   			 <p>Third paragraph (not red).</p>
		</div>		
		
Explanation: The <h1> is the second child of <div>, so the first <p> and third <p> will not be affected by p:nth-child(2).

Styling HTML Table with nth-child

Country Capital Continent
United States Washington, D.C. North America
France Paris Europe
China Beijing Asia
Brazil Brasília South America
Nigeria Abuja Africa
Australia Canberra Oceania
Antarctica None Antarctica

Reference