Utilizing Css Variables in Styled Components for Dynamic Styling

I have a particular component that looks like this:

const pretty = styled.div`
  --nth-child: 5n;
  --size: 20px; //css variable
  
  width: var(--size);

  &:nth-child(var(--nth-child)) {
    //...styles...
  }

  @media (max-width: 768px) {
    //overriding
    --size: 12px;
    --nth-child: 3n;
  }
`

The main question I'm facing is how to interpolate the CSS variable in this specific location?

&:nth-child(var(--nth-child)) {
  //...styles...
}

As far as I can tell, it seems impossible, so I'm looking for an alternative solution.

Please note: Using JavaScript variables is not an option in my situation.

Update:

The editor also highlights an error in that section:

https://i.sstatic.net/lb4W5.png

I attempted a workaround by trying this, but unfortunately, it didn't work either:

&:nth-child(${css`var(--nth-child)`}) {
  margin-right: 0;
}

Answer №1

Using CSS variables is limited to property declarations only, as they do not work in selectors.

However, there are alternative methods to achieve the desired outcome. If JavaScript variables are not an option and your situation is more complex than the example provided, consider utilizing React props interpolation with styled-components.

&:nth-child(${props => props.nthChildLargeScreen}) {
  //...styles...
}

@media (max-width: 768px) {
  &:nth-child(${props => props.nthChildLargeScreen}) {
    //...reverse styles from above...
  }

  &:nth-child(${props => props.nthChildSmallScreen}) {
    //...styles...
  }
}

Alternatively, consider using global variables:

&:nth-child(${NTH_CHILD_LARGE_SCREEN}) {
  //...styles...
}

...etc

If you can define styled components and CSS variables initially, you should be able to implement one of these alternatives instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embedding a Material-UI Icon into an Input Field within a React Application

Hello, I am currently using a datepicker provided by Material-UI Datepickers. When utilizing the Inline datepicker option, I would like to include a calendar icon within the input field. Below is the code snippet representing the input element. How can I ...

Angular JS Route Hijacking

Currently, I am developing an AngularJS application with Firebase as the backend system. One of my main goals is to require users to log in before accessing any part of the application. To achieve this, I plan on using Firebase's User Authentication ...

Getting the Current User in Django and Passing it to React

I have been working on a system that allows users to log in and utilize our service's features. To handle user authentication, we opted for Django Authentication. Here is the custom User model defined in my models.py - class UserDef(AbstractUser): ...

The Blueimp File Uploader seems to be sending numerous submissions at once

I've been tasked with fixing an issue on our site that I didn't originally build. The previous developer who worked on this project is now occupied with another task, leaving me to figure out what's going wrong. We are utilizing the basic bl ...

When using React's setState function, it sometimes fails to re-render with the most up-to-date data and instead shows

Encountering an issue with my class component where the state is not updating with the current user value on click, but rather displaying the previous value before updating. For example, if the initial value is set to 0 and I try to update it to 20 on clic ...

Switch up the attribute of an SVG element using jQuery

It has come to my attention that addClass and removeClass cannot be used with SVG, requiring the use of attr instead. However, I am facing a challenge in toggling an attribute of an SVG using jQuery. To see the specific issue I am encountering and my attem ...

Unable to display background image and color on Internet Explorer

The background beneath the slider and footer appears normal in most browsers, but there seems to be an issue with Internet Explorer. Check it out at this link: Do you have any suggestions on how to fix this? ...

Modify an individual attribute in a local JSON file using a put request in Angular 8

I am looking to make updates to my JSON file located in the assets folder. Specifically, if I want to update just one property of my JSON object, I would like it to only affect that particular property without impacting any others: For example, in the sam ...

Changing a variable's value to a string in JavaScript

Currently, I am utilizing a method in Tone.js that requires strings as arguments. Is there a way to define the variables at the beginning and then maintain them within their respective quotation marks? The following is the syntax that functions correctly: ...

Tips for enhancing your HTML email template with borders:

I designed an email template using the email template editor and incorporated nested table tags for each mail element. As I created a table to contain all these elements and attempted to add borders to the tags, I encountered a space between the top and bo ...

X-UA-Compatible feature implemented in a corporate intranet specifically designed to work seamlessly with Internet

My static HTML pages for a mockup design are functioning perfectly on their own in IE8, IE9, Chrome, Mozilla, and Safari. However, when I upload them to the server (WCS) for intranet development, they appear misaligned only in IE8 while displaying correct ...

``"Selecting a location upon clicking a marker in the array

I have limited experience with javascript but I am determined to improve my skills. Currently, I am facing a major roadblock in a project that I am working on and urgently require assistance. The project involves creating a map with marked locations from ...

The property 'muiName' is undefined and is throwing an error in the function t.isMuiElement

I'm encountering an issue while using Chrome browser. Uncaught TypeError: Cannot read property 'muiName' of undefined at t.isMuiElement (reactHelpers.js:31) The error occurs when I include <List> <ListItem> inside <DialogCont ...

Modifying hidden field values with JavaScript does not carry over to the server side in Chrome

I created a custom user control that contains a hidden field which is set when a node is clicked on a Tree View Hierarchy control. The following function is responsible for handling the click event of the Tree View: function HandleTreeClick(evt) { va ...

I am experiencing issues with my websocket connection following the deployment of my application

My frontend is built in React and my backend is in Node.js. Both are deployed on Vercel. The application runs smoothly locally, but I'm facing an issue when trying to replace the server-deployed link with my endpoint in the frontend. I am encounterin ...

Unable to modify background color in base website

While working on my project with Next.js, I encountered an issue where creating a button to change the color only affected the base web components' color and not the background color. _app.tsx import '../styles/globals.css'; import type { Ap ...

Creating an animated full-width SVG with a background image

This has been quite a challenge for me. I have successfully implemented the main functionality that I wanted in this codepen. The SVG is divided into 3 sections, with the middle section sliding away from the others when you click the "Find Out More" button ...

fetching server-side data for dynamic rendering

Having recently started working with Next.js and Firebase, I encountered a challenge in passing an id (Firebase auth) to getServerSideProps. Despite my efforts, I have been unable to retrieve the desired data. I attempted storing the id using js-cookie but ...

Visualizing nested data using dynamic line components in Recharts technology

Can the Recharts library handle nested keys? const data = [ { name: 'Sat Jan 1', curr: 4000, prev: 2400, }, { name: 'Sun Jan 2', curr: 3000, prev: 1398, }, ]; const data2 = [ { name: 'Sat Jan ...

Tips for preventing the use of Observable within another Observable

My service makes an http request that returns Observables of headlines. The code in my servise.ts file looks like this: servise.ts get(sort: string): Observable<Response> { return this.http.get<any>(this.url, {...}); }) delete(id) { ret ...