CSSで同じ値を複数個所で使用できるカスタムプロパティのまとめです。
oneクラス内で有効
.one {
--text-color: #333;
}
グローバルに有効
:root疑似クラスで定義
:root {
--text-color: #333;
}
大文字小文字は区別されます。
.one {
color: var(--text-color);
}
.two {
color: var(--text-color);
}
.three {
color: var(--text-color,#333);
}
もし、--text-colorが定義されていなかったら#333を使用する。
:root {
--color-dark1: #000;
--color-dark2: #888;
--dark-gradation: linear-gradient(var(--color-dark1),var(--color-dark2));
}
.three {
background-image: var(--dark-gradation);
}
<style>
@media print,screen {
.one {
--text-color: #f00;
color: var(--text-color);
}
}
@media screen and (max-width: 699px) {
.one {
--text-color: #0a0;
}
}
</style>
<h1 class="one">あいうえお<h1>
インラインスタイルから値を取得
element.style.getPropertyValue('--text-color');
あらゆる場所の変数を取得
getComputedStyle(element).getPropertyValue('--text-color');
インラインスタイルに値を設定
element.style.setProperty('--text-color', '#555');
<style>
.one {
--text-color: #f00;
--text-size: 20px;
color: var(--text-color);
font-size: var(--text-size);
}
</style>
<h1 class="one">あいうえお<h1>
<script>
const h1 = document.querySelector('h1');
//GET
const textColor = getComputedStyle(h1).getPropertyValue('--text-color');
console.log(textColor); //#f00
//GET
const textSize = getComputedStyle(h1).getPropertyValue('--text-size');
console.log(textSize); //20px
//SET
h1.style.setProperty('--text-color', '#00a');
//GET
const textColor2 = h1.style.getPropertyValue('--text-color');
console.log(textColor2); //#00a
//SET
h1.style.setProperty('--text-size', '50px');
//GET
const textSize2 = h1.style.getPropertyValue('--text-size');
console.log(textSize2); //50px
</script>