CSS, or Cascading Style Sheets, is a style sheet language used for describing the presentation of a document written in HTML or XML. CSS selectors are the building blocks of CSS, allowing us to select and style specific elements on a webpage. There are three main types of selectors in CSS: the element selector, the id selector, and the class selector. In this tutorial, we’ll take a closer look at each of these selectors and learn how to use them in our CSS.
CSS Element Selector
The element selector is the most basic type of selector in CSS. It targets all instances of a particular HTML element on a webpage. For example, if we wanted to target all the paragraphs on a webpage, we could use the following code:
1 2 3 4 5 6 |
p { font-size: 18px; color: #333; } |
In this example, we’re targeting all p
elements on the page and setting the font size to 18 pixels and the color to a darker gray color.
CSS ID Selector
The ID selector is used to target a specific element on a page based on its ID attribute. The ID attribute is a unique identifier for an HTML element, and no two elements on a page should have the same ID. To use the ID selector, we need to add a hash symbol (#) followed by the ID name to our CSS code. For example:
1 2 3 4 5 6 |
#header { background-color: #ebebeb; height: 120px; } |
In this example, we’re targeting the element with the ID of “header” and setting its background color to a very light gray and its height to 120 pixels.
CSS Class Selector
The class selector is used to target one or more elements on a page based on their class attribute. Unlike the ID attribute, multiple elements on a page can have the same class, and we can use the same class on different elements. To use the class selector, we need to add a period (.) followed by the class name to our CSS code. For example:
1 2 3 4 5 6 |
.article { border: 2px solid #ebebeb; padding: 12px; } |
In this example, we’re targeting all elements with the class of “article” and setting a border and padding around them.
CSS Selectors Summary
CSS selectors are essential tools for web developers, allowing us to target and style specific elements on a webpage. In this tutorial, we’ve learned about the three main types of CSS selectors: the element selector, the ID selector, and the class selector. By understanding how to use these selectors in our CSS, we can create beautiful, responsive, and engaging webpages.