How to pass a CSS variable correctly in nth-child?
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>
Is there a way to use the n value in :nth-child(n)?
CSS doesn't have support for variables. You could use Less/SASS loops and define it for n up to some value, but that would output almost the same CSS multiple times. Here is Codepen example.
SCSS code to support up to 10 cards:
$n: 10;
@for $i from 1 through $n {
.card:nth-child(#{$i}) {
position: absolute;
left: 10px * $i;
top: 10px * $i;
}
}
But are you sure your approach is correct? Maybe you want to take a step back and look for a different approach. Because this still doesn't scale dynamically, you'll have to predict or limit n to some value. If you were to pick large n, it would result in a big CSS file, which equals longer load times.
Use nth-child value as a SASS variable
I don't think there's a way to do exactly that. But you can use @for
directive to loop through a known number of elements:
$elements: 15;
@for $i from 0 to $elements {
div:nth-child(#{$i + 1}) {
background: rgb($i, $i, $i);
}
}
Related Topics
Tailwind CSS Classes Not Showing in Storybook Build
How to Use CSS Media Query to Scale Background-Image to Viewing Window
Maintain CSS Styling When Converting HTML to PDF in ASP.NET
MAC Safari 5.0.4 Bug When Using Google Maps API
Adding Hover Effects for Links in Image Map (Area)
What's the :Any-Link Pseudo-Class For
How to Use Fontawesome in Chrome Extension
Show :After When Hovering Over the Parent Element via CSS
Using Fractional Em's in CSS's Font-Size Property
Change Text Color Black to White on Overlap of Bg
Applying a Single Background Gradient to a Table Row
CSS Transform Scale, Don't Scale Child Element
Why Do /**/ Comments Work in Stylesheets But // Comments Don'T
CSS Calc - Round Down with Two Decimal Cases