CSS Selectors

CSS selectors are patterns used to select and style specific HTML elements. They are an essential part of CSS, enabling developers to apply styles to elements based on their tag names, classes, IDs, attributes, and even their relationships with other elements.

CSS selectors are used to select the content you want to style. Selectors are the part of CSS rule set. CSS selectors select HTML elements according to its id, class, type, attribute etc.

Key Points on CSS Selectors:

Syntax for CSS Selectors:

Syntax Example


/* Example: Styling multiple selectors */
h1, h2 {
    color: blue;        /* Applies blue color to h1 and h2 */
    font-weight: bold;  /* Makes text bold */
} 

Examples of CSS Selectors:

The following examples demonstrate various CSS selectors:

Code Example: Class Selector


.highlight {
    background-color: yellow; /* Highlights the background in yellow */
    color: black;            /* Sets text color to black */
}
        

Output

This is a highlighted paragraph.

Code Example: Attribute Selector


input[type="text"] {
    border: 2px solid blue; /* Adds a blue border to text inputs */
    padding: 5px;          /* Adds padding inside the input box */
}
        

Output

Code Example: Nth-Child Selector


ul li:nth-child(2) {
    color: red; /* Styles the second list item in red */
}
        

Output

  • Item 1
  • Item 2
  • Item 3

Code Example: Element Selector


p {
    font-size: 16px;       /* Sets the font size */
    color: blue;           /* Changes the text color to blue */
}
        

Output

This is a paragraph styled using an element selector.

Code Example: ID Selector


#uniqueHeading {
    font-family: Arial, sans-serif; /* Changes the font */
    color: green;                  /* Changes text color to green */
}
        

Output

This is a heading styled with an ID selector.

Code Example: Universal Selector


* {
    margin: 0;          /* Removes default margins */
    padding: 0;         /* Removes default padding */
    box-sizing: border-box; /* Sets box-sizing */
}
        

Output

Universal selector applies styles to all elements.

Example box styled with universal selector.

Commonly Used CSS Selectors:

CSS selectors provide the flexibility to target and style elements with precision, ensuring a consistent and visually appealing design across web pages.