8.3. Introduction to CSS: selectors, properties and values
Studying CSS (Cascading Style Sheets) is essential for any front-end developer. It is the language that gives style and layout to web pages, making them visually attractive and functional. In this chapter, we will focus on a fundamental aspect of CSS: selectors, properties, and values. Additionally, we'll explore the three main types of CSS selectors: Element, Class, and ID.
CSS Selectors
Selectors are the way CSS identifies the HTML elements it wants to style. There are several types of selectors, but we will focus on the main three: Element, Class and ID.
Element Selectors
Element selectors are the most basic. They select HTML elements based on their tag name. For example, if we want to style all paragraphs (<p>) on a page, we can use the 'p' element selector.
P { color: blue; font-size: 14px; }
In this example, all paragraphs on the page will be rendered in blue and with a font size of 14px.
Class Selectors
Class selectors are more specific than element selectors. They select HTML elements based on a class assigned to them. Classes are assigned to HTML elements using the 'class' attribute. For example, we can assign the 'highlight' class to a specific paragraph (<p>) like this:
<p class="highlighted">This is a highlighted paragraph.</p>
And then, we can use the '.highlight' class selector to style just that paragraph:
.emphasis { color: red; font-size: 18px; }
In this example, only the paragraph with the 'highlight' class will be rendered in red and with a font size of 18px.
ID Selectors
ID selectors are the most specific of all. They select a single HTML element based on an ID assigned to it. IDs are assigned to HTML elements using the 'id' attribute. For example, we can assign the ID 'title' to a specific header (<h1>) like this:
<h1 id="title">This is the title.</h1>
And then, we can use the '#title' ID selector to style just that header:
#title { color: green; font-size: 24px; }
In this example, only the header with the ID 'title' will be rendered in green and with a font size of 24px.
CSS Properties and Values
Once we select the HTML elements we want to style, we use CSS properties and values to define the style. Properties are aspects of the style that we want to change, such as color, font size, margin, padding, etc. Values are the specific settings we want to apply to these properties.
For example, in the CSS rule below:
P { color: blue; font-size: 14px; }
'color' and 'font-size' are properties, while 'blue' and '14px' are their respective values.
There are many different CSS properties and values to learn, and the right combination can create an endless variety of styles for your web pages.
In summary, CSS selectors, properties, and values are powerful tools in your front-end development arsenal. Understanding how they work and when to use them is key to creating visually appealing and functional web pages.