CSS ID Selector

An ID selector is a type of CSS selector that can be used to select a specific element on a web page.

ID selectors are unique, meaning that no two elements on a page can have the same ID.

To create an ID selector, you use the hash symbol # followed by the ID of the element you want to select.

Basic ID Selector

HTML
Try yourself
        
            <div id="my-element">This is my element</div>
        
    
CSS
        
            #my-element {
  color: red;
  font-size: 20px;
}
        
    

In this example, the ID selector #my-element targets the <div> element with the ID "my-element". It sets the text color to red and increases the font size to 20 pixels.


ID Selector with Element Type

HTML
Try yourself
        
            <h1 id="my-heading">This is my heading</h1>
        
    
CSS
        
            h1#my-heading {
  text-decoration: underline;
}
        
    

Here, the ID selector h1#my-heading targets the <h1> element with the ID "my-heading" and underlines the text.


ID Selector with Class

HTML
Try yourself
        
            <div id="my-element" class="my-class">This is my element with a class</div>
        
    
CSS
        
            #my-element.my-class {
  background-color: yellow;
}
        
    

In this example, the ID selector #my-element.my-class targets the <div> element with the ID "my-element"and class "my-class". It sets the background color to yellow.