Home > database >  How to insert div at the end of a grid?
How to insert div at the end of a grid?

Time:01-23

I have the following code:

.my-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-gap: 20px;
}

.item {
  background-color: #ddd;
  height: 300px;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>
<div >hello!</div>

Which looks like this in my testing:

enter image description here

Notice how the hello is on the next row.

Is there any way to instead have it inserted after the grid above? Such that it is the last grid item? Such that it is in line with it, instead of being on the next row.

The obvious solution is to just place the new-item div as a child of my-grid, but I cannot do that in my case, because my-grid is an external component from the internet, so I cannot insert something inside of it.

These two elements also have a common parent as well. Which can be anything.

CodePudding user response:

You can consider display: contents if they share the same container:

/* transfer all the styles to container 
   in the near future you can do .container:has(.my-grid) {}
*/
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-gap: 20px;
}

.item {
  background-color: #ddd;
  height: 300px;
}

/* we remove "my-grid" div*/
.my-grid {
  display: contents; 
}
<div >
  <div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
  </div>
  <div >hello!</div>
</div>

CodePudding user response:

You can set absolute position on "new-item" and if you have a div container above "my-grid" do not forget to set "position: relative", on it. Then you can adjust the left and top of "new-item", relative to the main div container. Might course some problem in different resolutions of the screen, adress it with some media queries.

  • Related