Search code examples
htmlcssflexboxcss-grid

Resize property on grid items results in overlap of other grid items


I have a CSS grid that is set to auto-fill the columns, to display as many items on a row as will fit.

This is done with: grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));

I would like to be able to resize selected grid items, which I am trying with:

resize: both;
overflow: auto;

This works at a basic level, but the content will overlap/stretch over adjacent grid items when resized horizontally:

Unwanted overlapping behaviour

When resized vertically, the rows below are instead pushed down, so there is no overlap: Wanted resize behaviour

This is the behaviour I want horizontally too.

I understand this is likely to do with using auto-fill for the columns, as when tracks are explicitly defined the stretching works the same on both axes.

.grid {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(auto-fill, 10em);
  /* grid-template-columns: repeat(auto-fill, minmax(10em, 1fr)); */
}

.grid>div {
  background-color: #eeeeff;
  padding: 0.5rem;
}

.resize {
  resize: both;
  overflow: auto;
}
<div class="grid">
  <div class="resize">Resize Me</div>
  <div>Item</div>
  <div>Item</div>
  <div>Item</div>
  <div>Item</div>
  <div>Item</div>
  <div>Item</div>
  <div>Item</div>
</div>

JSFiddle


Solution

  • You can use flex to achieve this:

    .grid {
      display: flex;
      flex-wrap: wrap;
    }
    
    .grid>div {
      border: 1px solid red;
      width: 150px;
    }
    
    .grid>div {
      background-color: #eeeeff;
      margin: 1em;
      padding: 10px;
    }
    
    .resize {
      resize: both;
      overflow: auto;
      border: 1px solid red;
    }
    <html>
    
    <body>
      <div class="grid">
        <div class="resize">Resize Me</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
        <div>Item</div>
      </div>
    </body>
    
    </html>