CSS selectors are used to "select" the HTML elements you want to style. There are several different types of selectors in CSS, each serving a different purpose. Here are some of the most common ones:
The universal selector (*
) applies to all elements on the page.
* { color: red; }
The type selector targets elements by their tag name.
p { font-size: 16px; }
The class selector targets elements with a specific class attribute. Use a dot (.
) before the class
name.
.classname { background-color: yellow; }
The ID selector targets a single element with a specific ID. Use a hash (#) before the ID name.
#idname { margin: 20px; }
The attribute selector targets elements with a specific attribute and value.
input[type="text"] { border: 1px solid #ccc; }
The descendant selector targets elements that are descendants of a specified element.
div p { color: blue; }
The child selector targets elements that are direct children of a specified element.
ul > li { list-style: none; }
The adjacent sibling selector (+
) targets an element that is the immediate next sibling of a
specified element.
h1 + p { font-size: 14px; }
The general sibling selector (~
) targets all siblings of a specified element.
h1 ~ p { color: green; }
Pseudo-classes target elements based on their state.
a:hover { color: red; }
Pseudo-elements target specific parts of an element.
p::first-line { font-weight: bold; }
By combining these selectors, you can apply styles to exactly the elements you want, giving you fine-grained control over the look and feel of your web pages.