Can we select the nth child in Tailwind CSS version 3 using any method?

I currently have 10 items that I am iterating through to display each one. I would like the opacity of the last element to be the lowest and the first element to be the highest. While I am familiar with using :first and :last in tailwind-css, I am curious if there is a way to target, for example, the 8th or 9th element using tailwind-css.

Below is the return statement from a component:

    {[0,1,2,3,4,5,6,7,8,9].map((item) => (
                            <section
                                key={item}
                                className='last:opacity-20 flex justify-between items-center text-slate-600 bg-white shadow-sm p-5 rounded-xl my-4 cursor-pointer dark:bg-black dark:text-slate-400'
                            >
                                <div className='flex gap-3 items-center'>
                                    <div className='rounded-full w-8 h-8 bg-slate-200'></div>
                                    <p className='w-44 h-4 bg-slate-100'></p>
                                </div>
                                <p className='w-16 h-4 bg-slate-100'></p>
                            </section>
                        ))}

My goal is to decrease the opacity as you move downwards the list, starting from the first item.

Answer №1

Using arbitrary variants is a great way to achieve this.

Take, for instance, the following code snippet:

<section className="[&:nth-child(8)]:opacity-25">
</section>

This will apply an opacity of 0.25 to a section element that is the eighth child.

Answer №2

Utilizing nth-child selectors is made simple with the introduction of Tailwind v3.2 and its matchVariant feature

// tailwind.config.js
let plugin = require("tailwindcss/plugin");

module.exports = {
  plugins: [
    plugin(function ({ matchVariant, theme }) {
      matchVariant(
        'nth',
        (value) => {
          return `&:nth-child(${value})`;
        },
        {
          values: {
            DEFAULT: 'n', // Default value for `nth:`
            '2n': '2n', // `nth-2n:utility` will generate `:nth-child(2n)` CSS selector
            '3n': '3n',
            '4n': '4n',
            '5n': '5n',
            //... add more if needed
          },
        }
      );
    }),
  ],
}

Example - elements with a 2n index will be styled in red, 1st, 6th, 11th, 5n+1 will be green, and every fifth element will be blue (note that styles may overlap demonstrating usage from configuration or arbitrary variants)

<ul class="">
  
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">1</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">2</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">3</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">4</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">5</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">6</li>

</ul>

LIVE DEMO

If you are using versions before 3.2, you will have to manually create a variant using addVariant for each nth-child selector

Answer №3

While the solution below does not utilize nth-child, it achieves the desired outcome: each list item will progressively decrease in opacity.

 {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item) => {
        // Create the class name dynamically
        // Tailwind configuration needed as outlined later
        const opacity = `opacity-${(10 - item) * 10}`;

        // Changed bg color to black for better visibility
        return (
          <section
            key={item}
            className={`${opacity} flex justify-between items-center text-slate-600 bg-black shadow-sm p-5 rounded-xl my-4 cursor-pointer dark:bg-black dark:text-slate-400`}
          >
            <div className="flex gap-3 items-center">
              <div className="rounded-full w-8 h-8 bg-slate-200"></div>
              <p className="w-44 h-4 bg-slate-100"></p>
            </div>
            <p className="w-16 h-4 bg-slate-100"></p>
          </section>
        );
      })}

Prior to rendering this content, make sure to update Tailwind's configuration file tailwind.config.cjs with the following settings:

const opacitySafeList = [];

for (i = 1; i < 11; i++) {
  opacitySafeList.push(`opacity-${i * 10}`);
}

module.exports = {
  content: ["...content of the project"],

// Instruct Tailwind to generate these specific class names that are not included by default 
  safelist: opacitySafeList,

  theme: {
    extend: {},
  },
  plugins: [],
};

This method (safe list) is typically a last resort according to Tailwind's guidelines, but it appears to be suitable for addressing this particular issue.

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

An empty canvas greeted me after successfully linking my React page to GitHub

After attempting to deploy my React web page on GitHub pages, I am now facing an issue where the page is not loading and only showing a blank screen. https://i.sstatic.net/9uz6oaKN.pnghttps://i.sstatic.net/UDo9GyME.pnghttps://i.sstatic.net/DaoUBdF4.pnghtt ...

Effective ways to sort material cards in Angular

Can someone guide me on how to implement a search bar in my Angular application to filter cards by name? Here is the link to my Stackblitz project for reference: https://stackblitz.com/edit/stackoverflowcom-a-60857864-6433166-dpaump Below is a snippet fro ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Issue with excessive content causing scrolling difficulty

I've created CSS for a modal dialog, but I'm facing an issue. When the content exceeds the vertical space of the wrapper, the scrolling functionality doesn't work correctly. Although I can scroll, it's limited and I can't reach th ...

The component is failing to detect that it is being exported

Encountering a strange error here. I exported the Home component in the usual way. See below for the relevant .js files to fix this error. However, the iOS simulator keeps showing the following error: Element type is invalid: expected a string (for built- ...

React hook form does not monitor a specific field within an array of fields

In my React Hook Form, I have an array of fields that includes a checkbox field. I want to be able to watch just that specific field, but currently I am only able to watch the entire array like this: const Period = ({ item, index, datepicker }) => { ...

The custom icon font sourced from Flaticon and hosted on a separate server is not functioning properly

I recently obtained a unique icon font from Flaticon and decided to incorporate it into a SaaS online store. Since I don't have direct access to the shop's files, I attempted to host the font on an FTP server and integrate it on a demo page: here ...

Encountering an issue in react.js where pushing the URL with ID is not possible due to a missing dependency in the useEffect hook array

I am encountering an issue where I am unable to successfully push the id with history.push in my React application. Strangely, if I omit the id, everything works as expected. This problem is occurring while using react-router-dom version 5. useEffect(() =& ...

Customize the InputFormat of the MUI DateTimePicker

I am trying to implement a custom InputFormat in the following manner 2018-01-05 13:08:00 This is an example code snippet <LocalizationProvider dateAdapter={AdapterDayjs}> <DateTimePicker renderInput={(props) => <TextField {... ...

Identify when a mouse hovers within 10 pixels of a div using jQuery

Is it possible to detect when a user hovers over a specific area within a div using JavaScript or jQuery, without adding any additional tags? -------------------------------- -------------------------------- -------------------------------- -------- ...

Is there a way for me to determine if something is hidden?

My goal is to have selector B toggle when selector A is clicked or when clicking outside of selector B. This part is working fine. However, I'm struggling with preventing selector B from toggling back unless selector A is specifically clicked - not w ...

Is it necessary to reload the page each time to see updates on the navbar in nextjs?

I recently developed a Next.js application with a Navbar component integrated into my layout.tsx file. The challenge arises when a user logs in and is redirected to the home page, which showcases a link in the Navbar for viewing their profile. However, I n ...

Utilize JavaScript's Map function to employ generalized keys in an array of objects

I am dealing with an array of objects that looks like this: [ { "job_id": 1, "job_name": "Engineer" }, { "job_id": 2, "job_name": "Scientist" }, ...

Emphasize the hyperlinked title

Is there a way to automatically add a CSS class "highlight" to headlines or sections based on anchors such as "...this.html#headline1" (similar to the table of contents on Wikipedia)? I am looking for a solution that will also work when navigating from a ...

Is it possible to use data() and attr() to retrieve original css in Firefox, but face issues in Opera and Chrome?

Is there a way to reset the position of a draggable div back to its original spot after it has been dragged using jquery ui's draggable()? I attempted this: $('#nav').draggable(); $('#nav').data({'x': $("#nav").css(&apo ...

How can I switch the values of two select components in React js when clicked?

I am working on a project where I have two select components positioned on the right and left side respectively, each with different values - A on the right side and B on the left side. Now, in response to a button click event, I need to swap component A t ...

Ways to prevent the inclusion of unnecessary fields in a graphql query when using Relay.createContainer

Currently developing a UI application using reactjs and integrating graphql for data retrieval. Utilizing Relay for this purpose, but encountering an issue where the graphql query created in Relay.createContainer is adding extra fields such as "id". Is the ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

Adjusting the text of a button when hovering over it will also trigger a resizing of the

Currently, I am facing an issue where the bootstrap button's size changes when hovered over. My intention is to have the bootstrap button remain a fixed size while only the text inside it changes using javascript for mouseover and mouseout events. How ...