'Make columns same height when stacked on top of each other Bootstrap 5

Is it possible to make columns the same height even when they turn into rows on mobile?

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
      <div class="col-sm-6" style="background-color:red">hi</div>
      <div class="col-sm-6" style="background-color:yellow">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ullamcorper odio a maximus ultrices. Sed vitae pellentesque mi. Aenean sit amet eleifend augue. Donec lobortis lacinia nibh, nec scelerisque turpis scelerisque a. Maecenas id aliquam ante. Sed nec ornare sem. In nec fermentum odio.
      </div>
    </div>

On a smaller screen, the columns would stack on top of each other. The one with text would be long.. but the empty one would disappear. How to I make them the same height?



Solution 1:[1]

Add following JS code:

if (window.screen.width <= 600) {
  const columns = document.querySelectorAll(".col-sm-6")

  const maxHeight = Math.max(columns[0].offsetHeight, columns[1].offsetHeight)

  columns.forEach(column => { column.style.height = `${maxHeight}px` })
}

Solution 2:[2]

I would prefer u to use media queries :D

so 1st give a same class to both of them like the following below:

 <div class="row">
    <div class="sm-same-height col-sm-6" style="background-color:red">hi</div>
      <div class="sm-same-height col-sm-6" style="background-color:yellow">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ullamcorper odio a maximus ultrices. Sed vitae pellentesque mi. Aenean sit amet eleifend augue. Donec lobortis lacinia nibh, nec scelerisque turpis scelerisque a. Maecenas id aliquam ante. Sed nec ornare sem. In nec fermentum odio.
      </div>
    </div>

and 2nd add some of the CSS like that :

@media screen and (min-width: 375px) {
  .sm-same-height{
    height:125px; 
   }
 }

(min-width: 375px) is the responsive size of mobile phone :)

hope it hepls you <3

Solution 3:[3]

Okay I found the answer already written on Stack Overflow. If you want to use CSS and don't know the height of the longest container, you can use CSS grid layout.

Equal height rows in CSS Grid Layout

Then I used this only on smaller screens

@media (max-width: 767.98px) { 
.row{
    display: grid !important;
    grid-auto-rows: 1fr;
}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konstantinos Gallis
Solution 2 DoYaKnowMe
Solution 3 Christine Wilson