Home > Blockchain >  Make columns same height when stacked on top of each other Bootstrap 5
Make columns same height when stacked on top of each other Bootstrap 5

Time:03-11

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 >
      <div  style="background-color:red">hi</div>
      <div  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?

CodePudding user response:

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` })
}

CodePudding user response:

I would prefer u to use media queries :D

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

 <div >
    <div  style="background-color:red">hi</div>
      <div  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

  • Related