Issue
Goal: Successfully pass a variable as a parameter to nth-child. In the example below, the third line should turn green.
Problem: Currently the parameter is ignored as a variable.
Question: Is this possible at all? If yes, what do I have to change?
Example Code:
:root {
--n: 3;
}
div p:nth-child(var(--n)) {
background: green;
padding: 10px;
}
<div>
<p>a</p>
<p>b</p>
<p>c</p>
</div>
Solution
The only place where you can use CSS custom properties (which are not "variables"!) is in declarations, after the :
. This also means that unfortunately you cannot use these custom properties in selectors, or in media queries.
That is also the reason why people really should stop calling them CSS "variables".
You can, however, manipulate styles using Javascript:
const dynamicStyles = document.getElementById('dynamicStyles');
const n = getComputedStyle(document.documentElement).getPropertyValue('--n');
dynamicStyles.textContent = `
div p:nth-child(${n}) {
background: green;
padding: 10px;
}
`;
:root {
--n: 3;
}
<style id="dynamicStyles"></style>
<div>
<p>a</p>
<p>b</p>
<p>c</p>
</div>
Answered By - connexo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.