0

I am using CSS Grid to display some tags. If a tag is large (ie. it's width is more than 150px), I would like that item to span into more columns as needed. For example, in the image I would like the red tag to span into two columns so that the text remains in one line.

Is it possible to do something like that without adding a specific class to the target element? I am mapping through an array in React to generate each of these divs so it won't be possible to add a class to that element only.

enter image description here

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;                                                       
}    

1 Answer 1

1

Don't know a way to implement a gradual column width increase via CSS only. A JS logic will be required to set "how many columns it should take". Then one of the following cases.

  1. explicitly style for the "wide" column:
grid-column: span X;

where X is how many columns should take your element.

  1. Set predefined classes (like at Bootstrap: col-1, col-2), then apply them.

If a column could have any width, then I would recommend you to use a flexbox with wrapping. Kind of:

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

Hope, this will help a little.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.