Skip to main content

CSS Selectors: Targeting Elements for Styling

CSS selectors are used to target specific HTML elements that you want to style.

Here are some of the most commonly used CSS selectors:

Element Selector

Targets all instances of a specific HTML element.

As an example:

p {
/* CSS styles go here */
}
  • This selector targets all <p> elements on a webpage.

Class Selector

Targets all instances of an HTML element with a specific class.

As an example:

.intro {
/* CSS styles go here */
}
  • This selector targets all elements with the class "intro", like this: <p class="intro">...</p>

ID Selector

Targets a specific HTML element with a unique ID.

As an example:

#header {
/* CSS styles go here */
}
  • This selector targets the element with the ID "header", like this: <div id="header">...</div>

Attribute Selector

Targets elements with a specific attribute or attribute value.

As an example:

input[type="text"] {
/* CSS styles go here */
}
  • This selector targets all <input> elements with the "type" attribute set to "text".

Descendant Selector

Targets elements that are descendants of a specific element.

As an example:

ul li {
/* CSS styles go here */
}
  • This selector targets all <li> elements that are descendants of a <ul> element.

Adjacent Sibling Selector

Targets an element that is immediately after another element.

As an example:

h2 + p {
/* CSS styles go here */
}
  • This selector targets the <p> element that immediately follows an <h2> element.

Universal Selector

Targets all elements on the page.

As an example:

* {
/* CSS styles go here */
}
  • This selector targets all elements on the page.

Child Selector

Targets elements that are direct children of a specific element.

As an example:

ul > li {
/* CSS styles go here */
}
  • This selector targets all <li> elements that are direct children of a <ul> element.

hover Pseudo-class Selector

Targets an element when the user hovers over it with their cursor.

As an example:

button:hover {
/* CSS styles go here */
}
  • This selector targets a <button> element when the user hovers over it with their cursor.

The :nth-child() Pseudo-class Selector

Targets elements based on their position within a parent element.

As an example:

li:nth-child(even) {
/* CSS styles go here */
}
  • This selector targets all even-numbered <li> elements within a parent element.

The :not() Pseudo-class Selector

Targets elements that do not match a specific selector.

As an example:

input:not([type="submit"]) {
/* CSS styles go here */
}
  • This selector targets all <input> elements that do not have a "type" attribute with the value "submit".