CSS Selectors

Week 2 - Learning about different CSS selectors

Types of CSS Selectors

CSS selectors are patterns used to select and style HTML elements. There are several types of selectors, each with different specificity and use cases.

Element Selector

The element selector selects HTML elements based on the element name.

Example: p { color: blue; } selects all <p> elements.

Class Selector

The class selector selects elements with a specific class attribute.

Example: .highlight { background-color: yellow; }

This is a highlighted text using a class selector.

ID Selector

The ID selector uses the id attribute of an HTML element to select a specific element.

Example: #unique-element { border: 2px solid green; }

This element has a unique ID and is styled differently.

Descendant Selector

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

Example: .container p { font-style: italic; }

This paragraph is inside a container and is styled with the descendant selector.

This nested paragraph is also affected by the descendant selector.

Child Selector

The child selector selects all elements that are the direct children of a specified element.

Example: .parent > span { font-weight: bold; }

This span is a direct child of the parent element.
This span is not a direct child, so it's not affected.

Adjacent Sibling Selector

The adjacent sibling selector selects an element that is directly after another specific element.

Example: h3 + p { color: blue; }

Adjacent Sibling Example

This paragraph is right after an h3, so it's styled with the adjacent sibling selector.

This paragraph is not directly after an h3, so it has normal styling.

Attribute Selector

The attribute selector selects elements with a specific attribute.

Example: [type="text"] { border: 2px solid purple; }

Pseudo-class Selector

Pseudo-classes are used to define a special state of an element.

Examples: :hover, :first-child, :last-child

Hover over this link to see the hover effect.

Pseudo-element Selector

Pseudo-elements are used to style specified parts of an element.

Examples: ::first-line, ::first-letter

This paragraph has its first line styled differently. This is a longer paragraph to demonstrate how the first line is affected by the pseudo-element selector. As you can see, only the first line has different styling.

This paragraph has its first letter styled differently. Notice how much larger and greener it is compared to the rest of the text.