8.6. Introduction to CSS: selectors, properties and values
CSS, or Cascading Style Sheets, is a style language used to describe the presentation of a document written in HTML. It is used to control the layout of multiple pages at once, allowing you to change the design of an entire website just by modifying one file. On our journey to becoming proficient front-end developers, it is crucial to understand how to use and understand CSS properties.
CSS Selectors
CSS selectors are the elements that define which HTML elements the style will be applied to. They can be divided into five categories: type selectors, descendant selectors, class selectors, ID selectors, and attribute selectors.
Type selectors
Type selectors select elements based on the HTML element name. For example, if we want to select all paragraphs on a page and change the text color to red, we can use the following code:
P { color: red; }
Descendant selectors
Descendant selectors select elements that are descendants of a specific element. For example, if we want to select only paragraphs that are inside a div, we can use the following code:
div p { color: red; }
Class selectors
Class selectors select elements based on their class. For example, if we want to select all elements with the class "red-text" and change the text color to red, we can use the following code:
.red-text { color: red; }
ID Selectors
ID selectors select an element based on its ID. For example, if we want to select the element with the ID "my-paragraph" and change the text color to red, we can use the following code:
#my-paragraph { color: red; }
Attribute selectors
Attribute selectors select elements based on a specific attribute and value. For example, if we want to select all links that point to "https://www.google.com" and change the text color to red, we can use the following code:
a[href="https://www.google.com"] { color: red; }
CSS properties and values
CSS properties are the styles you want to change, and CSS values are the styles you want to apply. For example, if we want to change the color of a paragraph's text to red, "color" is the property we want to change, and "red" is the value we want to apply.
There are many different properties you can change, including background color, font size, margin, padding, border, etc. Each property has a specific set of values that can be applied.
For example, if we want to change the font size of a paragraph to 16 pixels, we can use the following code:
P { font-size: 16px; }
If we want to change the background color of a div to blue, we can use the following code:
div { background-color: blue; }
It's important to remember that the order of styles in your CSS can affect the final result. If you have conflicting styles for the same element, the last style in your CSS will prevail.
Understanding how to use and understand CSS properties is an essential skill for any front-end developer. I hope this guide helped clarify some of the basics.