38
loading...
This website collects cookies to deliver better user experience
--main
is not the same as --MAIN
.--name: value
var()
function.var(--name, fallback)
name
is the variable name and fallback
is an optional value that will be used if the variable is invalid. The var()
function only accepts two arguments. Anything following the first comma is taken as the fallback value. However you can still define multiple fallback values.var(--name, red, black)
red, black
is the second argument and will be used just the same as if you were to just define red as the value and black as the first fallback. If you decide to used another variable as a fallback you cannot do the following:var(--name, --fallback-var)
--fallback-var
would be used and has no value when used outside the first argument of the var()
function. Instead you would need to do the following:var(--name, var(--fallback-var))
:root
pseudo-class as it gives the variable a global scope and thus can be used throughout the document. If you need to you can set a variable anywhere in the document but it will only be accessible within that element's local scope.:root {
--heading-color: red;
--paragraph-color: indigo;
}
h1 {
color: var(--heading-color);
}
p {
color: var(--paragraph-color);
}
#highlight {
color: var(--heading-color);
}
--heading-color
and --paragraph-color
are set under the :root
selector which gives them a global scope. The --heading-color
variable is then used as the color value for the h1
selector and the highlight
id, and the --paragraph-color
is used as the color value for the p
selector..getPropertyValue()
method. To set a variable value use the .setProperty()
method.// get root element
let root = document.querySelector(':root');
// get my-var value
root.style.getPropertyValue('--my-var');
// set my-var value to green
root.style.setProperty('--my-var', 'green');
:root {
--bg-color: white;
--text-color: black;
}
.dark-mode {
--bg-color: black;
--text-color: white;
}
const darkModeSwith = document.querySelector('#switch');
darkModeSwith.addEventListener("click", function () {
document.body.classList.toggle("dark-mode");
});
:root {
--margin: 25px;
}
@media screen and (min-width: 600px) {
:root {
--margin: 100px;
}
}
calc()
function along with CSS variables to easily set things relative to each other. If you wanted to make your heading twice the size of your paragraph font you could do the following.:root {
--paragraph-font: 14px;
}
h1 {
font-size: calc(var(--paragraph-font) * 2);
}