Home > OS >  Dynamic sizing of tiles using CSS
Dynamic sizing of tiles using CSS

Time:10-04

How to arrange video tiles in row and column (2 column per row) structure such that 1 video tile will take all the place available. However, if more video tiles are added dynamically they should follow the grid structure and the tiles should become smaller to not exceed the total area. For example in case of 3 video tiles, 2 tiles should be present in each column of first row and 1 tile should be occupying both columns in second row. Is it possible to implement this using CSS?

EDIT:

To simplify, let's consider divs instead of video tiles:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  max-width: 37.5rem; 
}

.grid > * {
  background-color: #ddd;
  margin: 0 0 1rem; 
  padding: .5rem;
  text-align: center;
}
<div class="grid">
  <div>I’ll find something to put here</div>
   <div>I’ll find something to put here</div>
   <div>I’ll find something to put here</div>
</div>

This works for even number of divs and they get arranged in 2 col per row. But for odd number divs, the remaining div does not take the entire row width.

CodePudding user response:

.grid {
  display: flex;
  flex-wrap: wrap;
}

.grid > * {
  flex:1 1 45vw;

  background-color: #ddd;
  margin: 0 0 1rem; 
  padding: .5rem;
  text-align: center;
}

here is it

CodePudding user response:

You can select the last element in the grid and specify at the same time that it must be an odd numbered one like this:

.grid div:last-child:nth-child(odd)

and give it twice the normal width.

You will have to think through what exactly you want to happen on narrow devices that can't accommodate two 'normal' divs side by side and not double the width.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  max-width: 37.5rem;
}

.grid * {
  background-color: #ddd;
  margin: 0 0 1rem;
  padding: .5rem;
  text-align: center;
}

.grid div:last-child:nth-child(odd) {
  width: 200%;
}
<div class="grid">
  <div>I’ll find something to put here</div>
  <div>I’ll find something to put here</div>
  <div>I’ll find something to put here I am last</div>
</div>

CodePudding user response:

Flex solution:

#flex {
    background: gray;
    display: flex;
    flex-wrap: wrap;
    width: 300px;
    height: auto;
}
  
#flex > * {
    background: blue;
    flex-grow: 1;
    height: 100px;
    width: 40%;
    margin: 10px;
    text-align: center;
}
<div id="flex">
    <div class="video"></div>
    <div class="video"></div>
    <div class="video"></div>
</div>

  • Related