Home / Articles / Blog

CodeCSSSelectorsFrontendProgramming

Top 10 CSS selectors

along with usecase and sample code

DesignShrey Vijayvargiya
text
/* Element Selector */
/* Selects HTML elements based on their tag names. */
/* Use Case: Applying a style to all paragraphs in a document. */
p {
    color: blue;
}

/* ID Selector */
/* Targets a specific HTML element by its unique id attribute. */
/* Use Case: Styling a specific element with a unique identifier. */
#special {
    color: blue;
}

/* Class Selector */
/* Selects HTML elements with a specific class attribute. */
/* Use Case: Styling elements that share a common class. */
.center {
    text-align: center;
}

/* Attribute Selector */
/* Targets elements based on their attribute values. */
/* Use Case: Styling links with a specific attribute. */
a[target="_blank"] {
    color: blue;
}

/* Descendant Selector */
/* Selects an element that is a descendant of another specified element. */
/* Use Case: Styling specific elements within a container. */
div p {
    color: green;
}

/* Child Selector */
/* Selects an element that is a direct child of another element. */
/* Use Case: Targeting specific elements that are direct children of a parent. */
ul > li {
    list-style-type: square;
}

/* Pseudo-class Selector */
/* Selects elements based on their state or position. */
/* Use Case: Styling links based on their hover state. */
a:hover {
    text-decoration: none;
}

/* Pseudo-element Selector */
/* Selects and styles a specific part of an element. */
/* Use Case: Adding custom styles to the first letter of a paragraph. */
p::first-letter {
    font-size: 150%;
    color: purple;
}

/* Universal Selector */
/* Selects all elements on the page. */
/* Use Case: Applying a style universally across all elements. */
* {
    font-family: Arial, sans-serif;
}

/* Group Selector */
/* Styles multiple elements with the same style definitions. */
/* Use Case: Minimizing code by grouping elements with shared styles. */
h1, h2, p {
    font-weight: bold;
}

Explore topics

More in

Weekly letter

Subscribe to iHateReading

Our once-a-week newsletter on programming, jobs, AI, and building products online.

Our once a week newsletter on Programming, Jobs, AI, and Business