Web Developer Interview Preparation

CSS Variables

Definition

Create Variables

We can make custom properties with values that can be used in other declarations. These property names are prefixed with –, and used in the var( ) function. 

  1. Define a root rule
  2. Put your variables inside of the root
(At the top of your CSS file)
:root {
	--first-color: hsl(175, 49%, 42%);
}

Different Types of Variables

  1. A regular variable has two dashes 
    • --second-color: #ffff8c;
  2. A custom variable has @ sign
    • @custom-media --min (width <= 600px);

Using Variables

// Using regular variables
#header {
	background-color: var(--first-color);
	color: var(--second-color);
}
// Using custom variables
@media (--min){
	display: block;
}

Create and Use a Custom Selector

...
	@custom-selector :--headings h1, h2, h3, h4, h5, h6;
}
:--headings {
	margin: 0 0 1rem;
	color: var(--first-color);
}

Create a more complicated variable

--my-button: {
	display: inline-block;
	padding: 6px;
	background-color: var(--first-color);
	...
}
.nav .my-button {
	@apply --my-button;
	@media (--min) {
		display: block;
	}
}

Note

This is one of the most useful features in CSS, but still new and experimental technology. Browser compatibility is pretty good, except for IE. You need the post CSS plug-in to make CSS variables work in IE. 

Reference

Do you know how to use CSS variables? [LINK]
Custom properties: CSS variables [LINK]

Leave a Reply

Your email address will not be published. Required fields are marked *