CSS Selectors

CSS Selectors

·

2 min read

  • CSS selectors are used to select the content the need to be style. Selectors are the part of CSS rule set. CSS selectors select HTML elements according to its attributes

There are several different types of selectors in CSS:

1. CSS Element Selector

The element selector selects the HTML element by name.

<style>  
p{  
    text-align: center;  
    color: blue;  
}   
</style>

2. The CSS id Selector

The id selector selects the id attribute of an HTML element to select a specific element. An id is always unique within the page so it is chosen to select a single, unique element.

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

<html>  
  <head>  
    <style>  
      #header1 {  
          text-align: center;  
          color: green;  
      }
    </style>  
  </head>  
  <body>  
    <h1 id="header1">Hello world</p>  
  </body>  
</html>

3. The CSS class Selector

The class selector selects HTML elements with a specific class attribute. It is used with a period character (.) followed by the class name.

<html>  
  <head>  
    <style>  
        .center {  
            text-align: center;  
            color: b;  
        }   
    </style>
  </head> 
  <body>  
    <h1 class="center">Hello World</h1>  
    <p class="center">This is paragraph</p> 
  </body> 
</html>

4. CSS Universal Selector

Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces.

  <style>  
    * {  
       color: green;  
       font-size: 20px;  
      } 
</style>

5. The CSS Grouping Selector

The grouping selector is used to select all the elements with the same style definitions.

<html>  
      <head>  
         <style>  
            h1, h2, p {  
                text-align: center;  
                color: blue;  
              }
          </style> 
      </head>  
      <body>  
        <h1>Hello world</h1>  
        <h2>welcome</h2>  
        <p>small quotes</p>  
      </body>
  </html>