You are currently viewing CSS Selectors – Everything you need to know

CSS Selectors – Everything you need to know

In CSS, selectors are used to select the HTML elements that we want to style on web pages. CSS rules can select for elements in many different ways. There are three basic kinds of selectors as follows:

type: to select HTML elements by element name

class: to select HTML elements by a specific class value

id: to select an HTML element associated with a specific id value

The type selector selects HTML elements based on the element name.

HTML
<html>
 <head>
   <title>Type Selectors</title>
 </head>
 <body>
   <p>Type selector to select element by its name.</p>
 </body>
</html>
CSS



p {
  color: green; 
}

CSS Class Selector

The class selector selects HTML elements with a specific class attribute. To select elements with a specific class, a period (.) character is written, followed by the class name.

HTML
<html>
 <head>
   <title>Type Selectors</title>
 </head>
 <body>
   <div class = "bordered">
     The She Coder
   </div>
 </body>
</html>
CSS



.bordered {
	border: 5px red;
  border-style:dashed;
}


CSS Id Selector

The id selector uses the id attribute of an HTML element to select a specific element .Since the id of an element is unique within a page, the id selector is used to select one unique element. To select an element with a specific id, a hash (#) character, followed by the id of the element is written.

HTML
<html>
 <head>
   <title>Type Selectors</title>
 </head>
 <body>   
   <div id = "idselector">
     <p>The id selector is used to select a specific element.
     </p>
   </div>
 </body>
</html>
CSS



#idselector {
	color:blue;
  border-color:black;
  border-style:solid;
}


               

CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

HTML
<html>
 <head>
   <title>Type Selectors</title>
 </head>
 <body>
   <h1>Universal Selector</h1>
   <p> The universal selector (*) selects all HTML elements on the page.
  </p>
 </body>
</html>
CSS


* {	color:blue;
  border-color:black;
  border-style:solid;
}



CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions to minimize the code. To group selectors, we separate each selector with a comma.

HTML
<html>
 <head>
   <title>Type Selectors</title>
 </head>
 <body>
   <h1>Universal Selector</h1>
   <p> The universal selector (*) selects all HTML elements on the page.
  </p>
 </body>
</html>
CSS


h1,p {	color:blue;
  font-style:italic;
}




Note: In the case where two (or more) selectors target the same element and property, CSS will select which property to apply based on its importance. id selectors are the most important, followed by class selectors, and finally, type selectors.