Reacting to a situation where the tailwind grid has an issue: the responsive column span is visible in the HTML, but

I'm having an issue with a grid that is not behaving as expected. I have set up a jsfiddle to show the behavior I am looking for, which relies on the responsive code: col-span-3 md:col-span-2 for one of the items.

The problem arises when I inspect the HTML and see that the dynamic breakpoints col-spans are present, but they are not working correctly when the viewport expands. What could be causing this issue?

This is how my component is wrapped:

<div className="max-w-5xl">
        <div className="grid grid-cols-6 gap-10 p-6">
          {
            supportedArray.map((card, idx) => <SupportCard key={idx} {...card} />
          )}
        </div>
</div>

Here is my SupportCard component:

import { ISupportCard } from "~/types"

const SupportCard = (card: ISupportCard) => {
  return (
    <div className={`bg-white card shadow-xl aspect-[portrait] overflow-hidden rounded-t-xl rounded-b-3xl col-span-${card.mobileSpan} md:col-span-${card.colSpan} ${card.customClasses ?? ""}`}>
      <div className="relative">
        <img className={`w-full h-full object-cover ${card.imgClasses ?? ""}`} src={card.image} alt={card.alt_text ?? card.title} />
        <h3 className="absolute text-neutralBlack bottom-0 flex justify-center items-center text-lg md:text-2xl font-bold bg-[rgba(255,255,255,0.5)] w-full card-title p-3 backdrop-blur">{card.title}</h3>
      </div>
      <div className="relative card-body hidden md:flex flex-1">
        <p className="text-xl font-medium">{card.copy}</p>
      </div>
    </div>
  )
}

export default SupportCard

This is the structure of the data sent to the component:

export interface ISupportCard {
  imgClasses?: string
  colSpan: number
  mobileSpan: number
  customClasses?: string
  title: string
  image: string
  alt_text?: string
  copy: string
}

One of the objects looks like this:

{
    colSpan: 6,
    mobileSpan: 3,
    imgClasses: "aspect-square md:aspect-auto object-[40%] md:object-fill",
    title: "Organizations",
    image: "/images/cards/support-organizations.jpg",
    alt_text: "Organizations",
    copy: `Copy...`
  }

Answer №1

According to the provided documentation:

An important point to note is how Tailwind extracts class names - it will only detect classes that are complete and unbroken strings within your source files.

If you try to interpolate strings or combine partial class names, Tailwind will not recognize them and thus will not create the corresponding CSS:

Avoid constructing dynamic class names

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

In the above example, the strings text-red-600 and text-green-600 are incomplete, so Tailwind will not generate those classes. Always ensure that the class names being used are complete:

Use full class names at all times

<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

You have options such as:

  • Create a dictionary for mapping col-span-* to Tailwind class names:

    const SupportCard = (card: ISupportCard) => {
      const COL_SPANS = {
        1: 'col-span-1',
        2: 'col-span-2',
        // …
      };
      const MD_COL_SPANS = {
        1: 'md:col-span-1',
        2: 'md:col-span-2',
        // …
      };
      // …
      return (
        <div className={`… ${COL_SPANS[card.mobileSpan]} ${MD_COL_SPANS [card.colSpan]} …`}>
    
  • Utilize the style attribute for properties that require true dynamism:

    const SupportCard = (card: ISupportCard) => {
      return (
        <div
          className={`… md:col-span-[--md-col-span] …`}
          style={{
            gridColumns: `span ${card.mobileSpan} / span ${card.mobileSpan}`,
            '--md-col-span': `span ${card.colSpan} / span ${card.colSpan}`,
          }}
        >
    
  • Safelist the classes if there are only specific known spans:

    module.exports = {
      safelist: [
        { pattern: /^col-span-[1-6]$/ },
        {
          pattern: /^col-span-[2-4]$/,
          variants: ['md'],
        },
        // …
      ],
      // …
    ];
    

Answer №2

To ensure that the class names are retained during purging and rendering on the website, it is necessary to declare them before the component is rendered in Tailwind CSS. This method allows us to continue using concatenation strings or literal templates.

let classNames = `grid gap-3 grid-cols-8 grid-cols-7 grid-cols-6 grid-cols-5 grid-cols-4 grid-cols-3 grid-cols-2`;

for(int i = 1; i<=8; i++)
    classNames = `grid gap-3 grid-cols-${i}`;

return(
    <div className={className}>
    // something
    </div>
);

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

Utilize itextsharp to transform HTML into PDF files

When I try to convert HTML to PDF using iTextSharp, the CSS styling I apply to the webpage does not get carried over to the converted PDF file. Here is the CSS code I am using: <style type="text/css"> .cssformat { ...

Creating a dynamic navigation bar that adjusts to changing content requires careful planning and implementation

Struggling with achieving my visual mockup while designing a webpage: Check out my web design mockup Currently focusing on section 2 of the page. Using Angular 5, Bootstrap 3, and ngx-bootstrap library to integrate Bootstrap components into Angular. Here ...

Effortlessly showcase JSON data in an HTML owl carousel

Is there a way to display JSON data in HTML format? I have a JSON file containing reviews from Facebook, and I would like to showcase them on my website. Each review should be placed in its own div element. The JSON data below is extracted from the Faceboo ...

Interactive calendar feature displaying events upon hovering over a date

I need some assistance with displaying a drop-down list on full calendar events when hovering over the events. Can someone provide guidance? Here is a glimpse of what I currently have: https://i.sstatic.net/fZXMH.png I've attempted setting the z-in ...

Struggling with generating a dynamic texture from an OffscreenCanvas in a Three.js shader

I'm currently tackling a React Three Fiber project where my goal is to render a dynamic texture from an OffscreenCanvas that's continuously updated in a WebWorker. However, I've encountered a roadblock as the render on my mesh appears black, ...

AngularJS allows users to easily select and copy all text from both div and span elements within a specified range. This feature makes it

I am working on implementing a select all feature using AngularJS for text displayed in a structure similar to the one below. Once all the text is selected, users should be able to press ctrl + c to copy it. <div ="container"> <div class="header ...

Loop through an array of div IDs and update their CSS styles individually

How can I iterate through an array of Div IDs and change their CSS (background color) one after the other instead of all at once? I have tried looping through the array, but the CSS is applied simultaneously to all the divs. Any tips on how to delay the ...

Overridden CSS rules

Having a slight CSS dilemma. Within my webpage's html, I have the following structure: <div class='box-div'> <div>Entry 1</div> <div class='hide'>Entry 2</div> </div> Here is my associated ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

Is it possible to utilize both the /app and /pages folders in my Next 13 application?

I am currently working on a project where the /app folder is utilized as the primary route container. However, we have encountered performance issues on localhost caused by memory leaks identified in an issue on the Next.js repository. I am curious to fi ...

Python Application Engine - Streamlining Responses from HTML Control Arrays

In my attempt to use App Engine (Python), I am facing a challenge in sending POST values from a variable array of select controls within an HTML form. Each select control is associated with a text describing what the user is rating. For instance, let&apos ...

Focus on targeting dynamic IDs such as #event_rules_attributes_0_interval, #event_rules_attributes_1_interval, etc. using CSS3 styling

Styling input tags using their IDs can be very convenient due to the higher precedence weight they hold compared to classes. For instance, I set a default width for input.text elements within a specific container: .details .metadata input.text { width: 2 ...

How can I guarantee consistent UTF-8 encoding in Nokogiri parsing, ERB templates, and encoding HTML files using Ruby?

After successfully parsing parts of a website, I encountered an issue with UTF8: get '/' do url = '<website>' data = Nokogiri::HTML(open(url)) @rows = data.css("td[valign=top] table tr") erb :muster I am now attempting ...

Demonstrate complete attendance by detailing specific days of presence and days of absence within a specified date range

In order to track the attendance of employees, I have a log that records when an employee is present or absent on specific dates within a given interval. Let's consider the following date range: $from = "2019-03-01"; $to = "2019-03-05"; Here is a ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

The complexities of stopPropagation() causing further confusion

I have encountered an issue with my code. It currently allows a dropdown functionality for a <ul> element, but when a child <li> is clicked, it also closes other menus of the same type. To fix this, I used an if clause to check if the clicked ...

Switch between webpage design for different devices (mobile/desktop) using javascript, jquery, and bootstrap

I am currently working on a webpage that contains various html elements with bootstrap classes applied to them. <div class="col-xs-12 col-lg-4"></div> My goal is to implement a button that, when clicked, will toggle the viewport/layout change ...

Storing raw HTML in a Mysql database, then fetching and displaying it on a webpage

I'm having an issue with my application. It's a form builder that allows users to create their own forms and then save them for later use. The HTML code generated by the form builder is stored in a MySQL database. However, when I try to retrieve ...

What is the best way to center a Bootstrap 4 navigation menu horizontally?

The alignment of the navigation is causing a bit of confusion. I've attempted to set the links to navbar-brand, but while this centers them, it also causes other elements to shift slightly downward. Additionally, it's puzzling why the select opti ...

Having trouble with the CSS :hover tag? Try changing the display property from none to inline-block

I'm currently working on a website navigation menu... I've decided to utilize the :hover feature in CSS to switch the display property from none to inline-block. In the past, I have implemented this with no issues whatsoever. However, I am now e ...