Understanding CSS Selectors

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:

1. Universal Selector

The universal selector (*) applies to all elements on the page.

* { color: red; }

2. Type Selector

The type selector targets elements by their tag name.

p { font-size: 16px; }

3. Class Selector

The class selector targets elements with a specific class attribute. Use a dot (.) before the class name.

.classname { background-color: yellow; }

4. ID Selector

The ID selector targets a single element with a specific ID. Use a hash (#) before the ID name.

#idname { margin: 20px; }

5. Attribute Selector

The attribute selector targets elements with a specific attribute and value.

input[type="text"] { border: 1px solid #ccc; }

6. Descendant Selector

The descendant selector targets elements that are descendants of a specified element.

div p { color: blue; }

7. Child Selector

The child selector targets elements that are direct children of a specified element.

ul > li { list-style: none; }

8. Sibling Selectors

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; }

9. Pseudo-classes

Pseudo-classes target elements based on their state.

a:hover { color: red; }

10. Pseudo-elements

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.