How to have a fixed element (like float: right) in a flex layout?

Viewed 141

I have a flex layout with elements in it. I want one of them to always stick in the top right corner. When I put it out of the container (below, in blue), it works for the basic cases, but in my last example, I would want the 5 box to be under the fixed one. How can I achieve that? Maybe with grid? I never used them. Another way to see it is to say that the space for that element should be reserved / not used by the flex elements.This way I could put the fixed one there with position: absolute; enter image description here

1 Answers

CSS grid can do this and the fixed element can be anywhere inside the container:

.container {
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
  grid-auto-flow:dense;
  grid-gap:5px;
}

.container > div {
  height:50px;
  background:red;
}

.container  .fixed {
  grid-column-end:-1; /* last column */
  grid-row:1; /* first row */
  background:green;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div class="fixed"></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Related