I am working on a CSS Grid layout where all child elements (buttons) must have the same width and height. The number of columns should automatically adjust based on the content of the child elements. Each button has text with varying lengths, but I want all buttons to have an identical size, capped by a max-height:
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
grid-auto-rows: 1fr;
gap: 10px;
}
button {
max-height: 80px;
}
<div class="container">
<button>
<div>Button 1</div>
<p>Description 1</p>
</button>
<button>
<div>Button 2</div>
<p>Description 2</p>
</button>
<button>
<div>Button 3</div>
<p>Description 3 Description 3 Description 3 Description 3 Description 3</p>
</button>
<button>
<div>Button 4</div>
<p>Description 4</p>
</button>
<button>
<div>Button 5</div>
<p>Description 5</p>
</button>
<button>
<div>Button 6</div>
<p>Description 6</p>
</button>
</div>
All buttons should remain identical in size (width and height), and the number of columns should adjust accordingly.
Is it something that can be achieved using CSS grid? if not what can be an alternative solution?
2
Answers
This set each button to a fixed height of 80px (instead of max-height) and uses flexbox for internal layout.
overflow: hidden is applied to the button to prevent content from expanding beyond the set height.
either add
overflow:hidden
to your button, it will keep themax-height
and cut your description accordingly, or remove the button css completely so all buttons will take the same height as the one with the largest description.