I am trying to learn about and work with CSS variables. I was wondering if it’s possible to nest several values inside a CSS variable to create a variable setting for a generic button to be used over and over. Here’s my scenario: I want to style a button that I will use repeatedly throughout my website. I have styled the button using variables like this:
:root {
--button1: #777;
--btnRadius: 7px;
--btnColor: #fff;
--padding: 12px;
}
.btn1 {
background-color: var(--button1);
border-radius: var(--btnRadius);
color: var(--btnColor);
padding: var(--padding);
}
In my “btn1” on the CSS sheet, I call all the values I want attributed to the button. Background color, font color, border radius and padding. This works fine. However, I am trying to figure out how to put all those values into a single variable and simply call the variable in my “btn1” styling. Something like this:
:root {
--ButtonStyle {
background-color: #777,
border-radius: 7px,
color: #fff,
padding: 12px;
}
}
.btn1 {
var(--ButtonStyle);
}
However, this obviously is not working. Is there a way to do this with variables in CSS? Thanks.
CodePudding user response:
I'm going to go out on a limb here and say you want to be able to change themes? If so then just create another list of variables. Then switch the theme and you will basically reload your btn1 class with the new variables.
document.getElementById('foo').onclick = function() {
document.documentElement.setAttribute("data-theme", "dark");
}
:root {
--button1: #777;
--btnRadius: 7px;
--btnColor: #fff;
--padding: 12px;
}
[data-theme="dark"] {
--button1: #555;
--btnColor: #000;
}
.btn1 {
background-color: var(--button1);
border-radius: var(--btnRadius);
color: var(--btnColor);
padding: var(--padding);
}
body {
background-color: var(--btnColor);
}
<body>
<button id="foo" >
Click Here to Change Theme
</button>
</body>