Skip to main content

Element Selectors in CSS

Element selectors in CSS allow you to target and style HTML elements based on their tag names. In this tutorial, you will learn how to use element selectors effectively, along with sample code and simple explanations.

Using element selectors

To target an HTML element using an element selector, simply write the tag name of the element in your CSS file. The styles within the declaration block will be applied to all instances of that element on the page.

Example:

CSS
/* Target all paragraph elements */
p {
font-family: Arial, sans-serif;
font-size: 16px;
}

In this example, the element selector p targets all paragraph elements on the page and applies the specified font-family and font-size styles.

Combining element selectors

You can target multiple HTML elements at once by listing the tag names as a comma-separated list. The styles within the declaration block will be applied to all instances of the listed elements.

Example:

CSS
/* Target all h1, h2, and h3 elements */
h1,
h2,
h3 {
font-family: 'Roboto', sans-serif;
color: darkblue;
}

In this example, the element selectors h1, h2, and h3 are combined to target all instances of these header elements and apply the specified font-family and color styles.

Element selectors with descendant selectors

Element selectors can be combined with descendant selectors to target elements that are descendants of other elements. This helps you apply styles more specifically based on the structure of your HTML document.

Example:

CSS
/* Target all paragraph elements within an article element */
article p {
font-size: 14px;
line-height: 1.5;
}

In this example, the element selector article p targets all paragraph elements that are descendants of an article element and applies the specified font-size and line-height styles.

Conclusion

In this tutorial, you learned how to use element selectors in CSS to target and style HTML elements based on their tag names. With this knowledge, you can effectively style your web pages and create consistent designs across various HTML elements.