#Use component prop value in CSS :nth-of-type selector?

1 messages · Page 1 of 1 (latest)

wise viper
#

I have a component that is being passed an integer value as a property, and I'm trying to create a CSS rule that uses it in its :nth-of-type selector:

---
interface Props {
    active?: number;
}

const { active = 1 } = Astro.props;
---

<style>
  nav a:nth-of-type({active}) {
    /* ... */
  }
</style>```

I have also tried passing it in as a CSS variable, as per https://docs.astro.build/en/guides/styling/#css-variables, however the selector itself seems to not support CSS variables as valid syntax:

```<style define:vars={{active}}>
  nav a:nth-of-type(var(--active)) {
    /* ... */
  }
</style>```

Sadly neither of these work. Is there a clean way to do this? I would prefer to avoid applying these CSS rules via JS...
bitter iron
#

Seems using vars like that isn't possible from CSS like you said. If you really don't want to use JS, see if you can change the component structure where you don't need to use that selector e.g. pass an active boolean prop, or use a class name

wise viper
#

unfortunate, guess I'll work around it by using JS to add a class to the element I want to affect

abstract sphinx
#

Hold on, from the server, are you able to spit out something like data-active="something", meaning at least you know how that nth-child will be, per markup? Then plain CSS or Tailwind should be able to select it. Would question then be of how to write the selector?

wise viper
#

where would I add this? to the <nav> element?

abstract sphinx
#

You mean where will you add the CSS? You don't want to do so in style tag? If Tailwind, then yes, your nav element should be fine?

wise viper
#

no I meant the data-active="something"

abstract sphinx
#

data-active={ const-nth-child-value } something like that... since you know the value a css construction like [data-active="const-nth-child-value"] should be fine or a construction along those lines depending what you want to target/style

wise viper
#

but I still can't pull that value out and use it in an :nth-of-type selector. I'd have to create a selector along the lines of

nav[data-active="2"] a:nth-of-type(2),
nav[data-active="3"] a:nth-of-type(3),
nav[data-active="4"] a:nth-of-type(4)```

repeat for however many elements I might have in my nav bar
abstract sphinx
#

I don't know if I must have missed your original premise (of what you wanna achieve) but aren't just trying to target the "active" element and style/do (something to) it somehow?