Search code examples
javascripthtmlcssgrid-layout

How i can positionate blocks like on picture with dynamic quantity with css or javascript


Positioning blocks

I want to positionate my blocks like on picture with css or javascript. Four blocks is maximum in one line and other justify like on picture. What do i need to achieve this.

I tried to positionate it with flex, but flex haven't column-gap yet. Also justify-content doesn't help me, because it this case blocks have different gaps. Maybe it can positioning with grid, but I know that you can only hardcode values in css with grid-area or grid-column, but its only works with static quantity.

ul {
  display: grid;
  grid-template-columns: repeat(8, 55px);
  grid-template-rows: 1fr 1fr;
  grid-gap: 25px;
  list-style: none;
}
li {
  width: 100%;
  height: 50px;
  background: #c4c4c4;
  border-radius: 10px;
}
li:nth-child(1) {
  grid-column: 1/3
}
li:nth-child(2) {
  grid-column: 3/5
}
li:nth-child(3) {
  grid-column: 5/7
}
li:nth-child(4) {
  grid-column: 7/9
}
li:nth-child(5) {
  grid-column: 2/4
}
li:nth-child(6) {
  grid-column: 4/6
}
li:nth-child(7) {
  grid-column: 6/8
}
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

I need solution which will work for different quantity, but now i have only for static


Solution

  • With justify-content: center, you do have to give it a margin so they don't stick to each other. It can be achieved but I don't know if you'd prefer. Check my snippet to see what I'm talking about.

    ul {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      list-style: none;
    }
    
    li {
      width: 20%;
      height: 50px;
      background: grey;
      border-radius: 10px;
      margin: 10px;
    }
    <ul>
      <li></li>
      <li></li>
      <li></li>  
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>