4

I'm currently facing a problem with CSS grid. I'm looking here on Stackoverflow or Google for hours and can't find relevant and correct solution.

My goal is to achieve this behavior:

In the beginning are all of the elements in a row, but when I start to shrink the screen (responsivity), then I want to make element which doesn't fit wrap to the next row. (Basically the last element, in this case the link). This behavior which I want to achieve is just like display flex's attribute flex-wrap:wrap.

In all of the articles I've been searching they were using fixed width of columns, but my goal is also to make it kind of "automatic" just like when you use display:flex. (I don't really know how long will be the texts. Texts will be sent to this component via props)

To wrap it up:

My goal is to make display:grid automatically detect how many columns it has to make (how many children are there) and automatically wrap element to new row, when there is no space for it.

Is this even possible?

.notification{
  background:lightgreen;
  padding:1rem;
  display:inline-block;
}

.notification-body{
  display: inline-grid;
  grid-auto-flow: column;
  grid-column-gap: 1rem;
  align-items: center;
}

.notification-content-wrapper{
  display: inline-grid;
  grid-auto-flow: column;
  /*this is supposed to work according to other articles..*/
  grid-template-columns: repeat(auto-fit, minmax(max-content, 0px));
  grid-column-gap: 1rem;
  align-items: center;
}
<div class="notification">
  <div class="notification-body">
    <p>there will<br>be always icon</p>
    
    <div class="notification-content-wrapper">
      <p>Notification message</p>
      <a href="#">notification link</a>
    </div>
    
    <p>there will be<br>always icon too</p>
  </div>
</div>
Pinnci
  • 423
  • 2
  • 5
  • 20

2 Answers2

0

As mentioned here (CSS grid wrapping) by Ricky:

repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )

Check out their answer for a more detailed explanation.

  • I've seen that post, but i quite dont understand it. Ricky is also using fixed width which I simply cant – Pinnci Nov 04 '21 at 15:34
  • Please provide a working example so someone else can pickup the issue and propose a solution – Cássio Nov 04 '21 at 19:45
  • Maybe you're trying to make a masonry grid? [Mdn Masonry Grid](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout) I'm not sure why else you wouldn't have some max length to help the columns wrap – Aaron Rine Nov 08 '21 at 20:43
0

You have to use auto-fit and don't use grid-auto-flow property, if you want to control the height of the new rows you must use grid-auto-rows. That should work don't mix alot of grid properties together.