Search code examples
htmlcsslayoutgridfloating

How to place Cards by Mosaic way?


The height every of the card needs to be max-content.

I've set height to specific values for demonstrating the problem.

.container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-column-gap: 5%;
    grid-auto-rows: min-content;
}

.card {
    background-color: lightblue;
}
<div class="container">
	<div class="card" style="height: 100px">
		1
	</div>
  <div class="card" style="height: 200px; background-color: yellow">
		2
	</div>
  <div class="card" style="height: 200px; background-color: yellow">
		3
	</div>
  <div class="card" style="height: 200px">
		4
	</div>
  <div class="card" style="height: 200px; background-color: green">
		5
	</div>
  <div class="card" style="height: 200px; background-color: red">
		6
	</div>
  <div class="card" style="height: 200px">
    7
	</div>
</div>

The problem is - There is a White space between 1 and 3 cards. Need to achive - no this extra white space. Card 3 needs to be excactly after 1

I've tried - grid-auto-rows: min-content - but it makes no result.

Cards with different height need to be exactly one after another one. without extra white space. (By Mosaic way).


Solution

  • What you're trying to achieve is called Masonry Layout.

    You'll find a lot of example here https://css-tricks.com/piecing-together-approaches-for-a-css-masonry-layout/ I hope it will help you to find which option better fits your needs.