Learn CSS

"If you want to learn how to style and design web pages, you need to master CSS. CSS stands for Cascading Style Sheets, and it is the language that defines the appearance and layout of HTML elements. In this course, you will learn the basics of CSS, such as selectors, properties, values, units, and colors. You will also learn how to use CSS to create responsive web design, animations, transitions, and more. By the end of this course, you will be able to create beautiful and functional web pages using CSS."

CSS Variables - The var() function

CSS Variables, also known as CSS custom properties, allow you to define a value once and reuse it multiple times throughout your CSS stylesheet. They offer a convenient and powerful way to manage your styles, make global changes easily, and maintain consistency across your design.



They are represented by two dashes (--) followed by the variable name, and their values can be used throughout your stylesheet using the var() function.

Here's the syntax for creating a CSS variable:

:root {
 --variable-name: value;

The :root pseudo-class is used to define the variable globally for the entire document. The variable name can be any valid CSS identifier, and the value can be any valid CSS value.



To define a CSS variable, you can use the -- prefix followed by a name for your variable, and assign it a value:

:root {
 --primary-color: #007bff;

In this example, we define a variable named --primary-color with the value #007bff. The :root selector is used to define the variable globally, so it can be used anywhere in the stylesheet.

Once you have defined a variable, you can use it in your styles by referencing it with the var() function:

button {
 color: var(--primary-color);
 background-color: white;
 border: 1px solid var(--primary-color);
 padding: 0.5rem 1rem;

In this example, we use the var() function to reference the --primary-color variable in several places. This way, if we want to change the primary color, we only need to update the value of the variable, and the styles that use it will be updated automatically.

You can also specify a fallback value for a variable in case it is undefined or not supported by the browser:

button {
 color: var(--primary-color, black);

In this example, if the --primary-color variable is not defined or supported, the color property will use a fallback value of black.

CSS variables can be used to define and reuse values for any CSS property, including font sizes, margins, padding, box shadows, and more. They can also be used with media queries to create responsive designs that adjust to different screen sizes and devices.

Overall, CSS variables are a powerful and flexible feature that can help you streamline your styles, increase consistency, and make your code more maintainable.