How to use CSS Selectors for styling elements?

Using CSS selectors, we can specifically style desired elements based on our preference. There are various methods for selecting elements in the HTML DOM. The CSS Selectors include −

  • Class selector

  • Id selector

  • Grouping Selectors

Syntax

The syntax for CSS selectors is as follows −

Selector {
   /*declarations*/
}

CSS class selector

The class attribute is used to set the class selector. This will select a specific element. You need to write the . i.e., the period character and follow it by the class attribute to select the element with a specific class −

Example

<!DOCTYPE html>
<html>
<head>
   <style>
      .circle {
         width: 100px;
         height: 100px;
         background: rgb(0, 255, 13);
         border: 3px solid rgb(27, 0, 78);
         border-radius: 50%;
      }
   </style>
</head>
<body>
   <h1>Create a Circle</h1>
   <div class="circle"></div>
</body>
</html>

CSS id selector

The id attribute is used to set the id selector. This will select a specific element. You need to write the # character and follow it by the id to select the element with a specific id −

Example

<!DOCTYPE html>
<html>
<head>
   <style>
      #one {
         filter: invert(85%);
      }
   </style>
</head>
<body>
   <img id="one" src="https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg">
   <img src="https://www.tutorialspoint.com/plsql/images/plsql-mini-logo.jpg">
</body>
</html>

CSS Grouping Selectors

The elements on a web page can be styled together using the grouping selectors. You need to separate each selector by a comma −

div, p {
   margin: 4px;
   float: left;
   height: 200px;
   width: 300px;
   box-shadow: inset 0 2px 4px olive;
   background-image: url("https://www.tutorialspoint.com/sas/images/sas-mini-logo.jpg");
}

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <style>
      div, p {
         margin: 4px;
         float: left;
         height: 200px;
         width: 300px;
         box-shadow: inset 0 2px 4px olive;
         background-image: url("https://www.tutorialspoint.com/sas/images/sas-mini-logo.jpg");
      }
      p {
         background-image: url("https://www.tutorialspoint.com/qlikview/images/qlikview-mini-logo.jpg");
         background-position: 50% 50%;
         color: black;
      }
   </style>
</head>
<body>
   <h2>Learning Tutorials</h2>
   <div></div>
   <p>Tutorials</p>
</body>
</html>
Updated on: 2023-12-21T15:08:20+05:30

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements