Effortlessly adjust item width in CSS Grid

I am currently utilizing CSS Grid to showcase various tags. If a tag happens to be quite large, with a width exceeding 150px, I would ideally like that specific item to expand across multiple columns as necessary. For instance, in the visual representation, I envision the red tag extending into two columns so that the text remains on a single line.

Is there a way to achieve this effect without assigning a dedicated class to the target element? Given that I am iterating through an array in React to create each of these divs, it seems impractical to apply a class solely to that element.

https://i.stack.imgur.com/PILvY.png

index.js

<div className={styles.container}>                      
  <>                                                  
    {tags.map(tag => {                              
      return <TagBlock tag={tag} />               
    })}                                             
  </>                                                 
</div> 

style.css

.container {                                                              
   margin: 30px auto;                                                      
   width: 90%;                                                           
   display: grid;                                                        
   grid-template-columns: repeat(auto-fill, minmax(150px, auto));        
   grid-gap: 20px;                                                       
}    

Answer №1

To increase column width gradually using CSS only, you may need to implement a JS logic to determine the number of columns your element should span. In such cases, you can either explicitly style the "wide" column like this:

grid-column: span X;

where X represents the number of columns your element should occupy.

  1. Alternatively, you can use predefined classes (e.g., col-1, col-2) similar to Bootstrap and apply them accordingly.

If the column width is variable, consider using flexbox with wrapping. For example:

.container {
   margin: 30px auto;
   width: 90%;                                                           
   /*additional properties below*/
   display: flex;                                                        
   flex-wrap: wrap;
   align-content: flex-start;
}
/*TagBlock base style that grid generates on its own*/
TagBlock {
  margin: 25px;
  min-height: 120px;
  min-width: 120px;
}

I hope this provides some guidance for your implementation.

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

When the content div is clicked within the overlay div, the popup will also close

I want to design a pop-up that features a container with a black background and some opacity, where the content of the popup is placed inside. Here's what I have in mind: <button (click)="showPopup = !showPopup">Open popup</button& ...

Collapsing borders in JavaFX 8

Hey there! I'm having a little issue with JavaFX 8 components. I'm trying to make them sit next to each other with borders, but it's not quite working out. Is there a way to make them blend together and share one border? import javafx.geome ...

Dealing with extended render times in React applications

Currently, I'm working with a limited set of 100 documents per page and utilizing a wrapper component for certain conditional actions. const onClickCheckbox = (order: OrderProps) => { const _ordersToExport = [...ordersToExport]; const ind ...

Scrolling automatically within a child element that has a maximum height limit

I am currently developing a console/terminal feature for my website. https://i.stack.imgur.com/AEFNF.jpg My objective is to allow users to input commands and receive output, which might consist of multiple lines of information. When new output is displa ...

Utilizing :checked selector and toggle() function in jQuery

I'm facing an issue with my jQuery code where the CSS changes are not working as expected. When I test the code, it doesn't apply the CSS changes. If I remove the :checked and just use $("input"), then the CSS works but only when clicking on an i ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Deploy the Next.js app on Vercel without regenerating pages, and instead trigger the deployment only upon request

Greetings to my fellow developers, For the past year, I have been using Next.js on Vercel and so far, I am absolutely loving it. The ability to create SEO friendly React websites has been a game changer for me. However, as my website continues to grow and ...

Styling a specific element in Svelte without needing a globally unique identifier

How can I target just the outer div using a css selector? <div> <div>...</div> <div>...</div> </div> <style> OUTER.DIV.ONLY { background: url(outer.png); } </style> Alternatively, I& ...

How can I transform Material UI pure ReactJS functions into ES6 classes?

I have integrated React Material UI into my application and encountered some missing logic in my React code. The code provided below is functioning correctly. import React from 'react'; import { fade,makeStyles } from '@material-ui/core/sty ...

Unusual gaps of white space appearing between React components

Currently developing a small web application with multiple components. The backend functionality is all set, but encountering an unusual styling issue. Specifically, noticing a white space appearing between each component without any clear reason. This ga ...

The error encountered is: `Exception: startDate.getTime is not a valid function

const [currentDate, setCurrentDate] = useState(new Date()); const fetchDataFromAPI = () => { let timeStamp = Number(currentDate.getTime()); axios.get( `https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD,EUR& ...

What is the best way to position the left sidebar on top of the other components and shift them to the

Currently, I am working on a project to display NBA data fetched from an API. I am aiming to recreate the design showcased here: Dribbble Design My main challenge lies in overlaying the left sidebar onto the main box and shifting the components sligh ...

How to Change the Appearance of Elements in an Array Using React.js

My situation involves an array receiving data from an API, and I'm looking to customize each button's appearance by giving them different background colors. In addition, my project includes Material UI... Below is the snippet of code I have - {op ...

Utilize dynamic properties in zod depending on the current state

I have an object that may contain one of two properties depending on a state in react known as state. I am attempting to incorporate this into the Zod schema to generate an error if either property is empty or undefined based on the state. Data.ts const d ...

React - discrepancy in date-fns' differenceInDays function resulting in a NaN output

For some reason, I am encountering a NaN error when attempting to calculate the difference in days between the current date and a product's expiry date in the user's timezone. I have included my code below for reference: import { formatInTimeZone ...

What is the functionality of bootstrap colors?

Recently, I've been practicing my skills with Bootstrap, and I'm determined to understand all aspects of the code. However, one thing that's currently puzzling me is the navbar colors. When I apply the navbar-dark class, instead of displayin ...

Dimensions of CSS Buttons

On my screen, I have 3 buttons with varying sizes determined by their padding. As the text wraps within each button, they adjust in height accordingly. However, the issue arises when the buttons end up being different heights. Instead of setting a specific ...

Designing a scrollbar for a tr element using HTML and CSS

I am struggling to create a scrollbar for the inner table that is not being displayed within its container. The container has a yellow background while the table itself is blue. My goal is to have a scroll bar specifically within the table. For more info ...

How come my Next.js route handler is not able to access the request body from my button component?

I'm having difficulty extracting the request body from a route handler in Next.js 13. Below is my button component: 'use client' export default function Button() { const handleClick = () => { const requestOptions = { ...

React Conditional Rendering: What Sets It Apart

When it comes to conditionally rendering a React component, there are two common approaches: const SomeComponent = ({isReady}) => { if (!isReady) { return null; } return ( <div> ..rest of component elements </div> ) ...