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

Tips for showing grouped headers in MUIDatatable using React JS

enter image description here Looking at the image above, I am trying to display it in a muidatatable with grouped headers. I attempted to use the code below but was unsuccessful in creating a table with grouped headers; it only displayed the individual h ...

CSS: Adjusting the top margin of a font

I admit, the title of this question may not be the most creative, but I've hit a wall in my search for answers. It seems like I must be missing something fundamental in CSS, or perhaps my search terms are just off. Here's the issue: I have a con ...

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Is passport.js necessary if I am implementing Auth0 for authentication in my React application?

While passport.js is commonly used for server side authentication, if I am already utilizing Auth0 as the authentication service for my React application, do I still require passport.js? ...

Struggling with implementing responsive mobile buttons that stack in a column? Here's the solution

My content is nearly responsive on all screen sizes, but I'm having trouble getting the buttons to stack neatly in a column. Can anyone provide suggestions on how to fix this issue? You can view the current progress below. Thank you in advance for any ...

What is the best way to conditionally wrap a useState variable in an if statement without losing its value when accessing it outside the if block in reactjs?

I am facing a coding challenge with my cards state variable in React using the useState hook. I tried adding my array data to it but ended up with an empty array. Placing the state inside an if statement resulted in undefined variables. I attempted various ...

The height of the href is not displaying correctly when the text-decoration is disabled and it is placed next to

In my design, I have a link positioned next to an image with perfect vertical alignment. Everything looks great when the text has the standard text-decoration, centered vertically and all that. However, as soon as I remove the text-decoration, leaving the ...

What is the best way to implement this design using CSS flexbox?

I'm working on designing a simple layout that looks like this: https://i.stack.imgur.com/oCzyV.png Currently, I have the following HTML structure with some variations in class names and additional markup within each element: <div class="site ...

Sass does not compile for optimization

My Sass compiler generated an overly large file for me, but it could be much smaller!! I checked the compiler settings and didn't find anything wrong! The issue might be with the compiler itself. It's also possible that there is a problem with my ...

Ways to eliminate the lower boundary of Input text

Currently, I am working on a project using Angular2 with Materialize. I have customized the style for the text input, but I am facing an issue where I can't remove the bottom line when the user selects the input field. You can view the red line in t ...

How long does jQuery animation last until completion?

Within my project, I am utilizing the animationComplete function from the jQuery mobile library. You can find this function at The animation in my project involves a sequence of objects with various tasks to be executed at each point of the animation. The ...

Need to delete the product page link on WooCommerce?

I am currently working on fixing the one-page checkout process and I need to remove a single product link from a product picture. The goal is to have only the checkout link displayed on this page, specifically within a quickview view. After trying out var ...

Creating interactive form fields using React

How can I update nested fields in react forms? First, create a new item using handleAddShareholder. Next, delete an existing item with handleRemoveShareholder. To change details of an item, use handleShareholderNameChange. You can then add a new array ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Guide on how to use a tooltip for a switch component in Material-UI with React

I am attempting to incorporate a tooltip around an interactive MUI switch button that changes dynamically with user input. Here is the code snippet I have implemented so far: import * as React from 'react'; import { styled } from '@mui/mater ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

What is the best way to manage image storage when creating an app using node Express, React, and MySQL?

Currently developing an app using Express, React, and MySQL for a tattoo shop. The app includes a Content Management System (CMS) that allows management and employees to add photos to portfolio pages, update artist information, and manage artists. Addition ...

How is it possible to encounter a missing semicolon CssSyntaxError during a Gatsby build?

Currently, I am in the process of developing a Gatsby page with Material UI. The design of the page is almost finalized; however, upon completing the project, an unexpected build error occurs when running npm run build. WebpackError: Pathname: /invitation/ ...

Error in React Toaster preventing redirect with useHistory() before reaching another page

When I try to display a message using react toaster and then redirect to another page using history.push('/'), the toaster fails to work properly. Instead, the page immediately redirects to the homepage without displaying the toast message first. ...