Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make every two elements the same height

I have a container with a number of children that needs to be the same height, only in pairs of two tho. for example the first and second element needs to be as high as the highest of the two and the third and forth need to be as high as whichever is highest, independent of the height of the first and second child.

My current code, which equals all children heights

$(document).ready(function(){
        // Select and loop the container element of the elements you want to equalise
        $('.parent').each(function(){

            // Cache the highest
            var highestBox = 0;

            // Select and loop the elements you want to equalise
            $('.child', this).each(function(){

                // If this box is higher than the cached highest then store it
                if($(this).height() > highestBox) {
                    highestBox = $(this).height();
                }

            });

            // Set the height of all those children to whichever was highest
            $('.child',this).height(highestBox);

        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
</div>
like image 231
Christian Andernsen Avatar asked May 18 '26 18:05

Christian Andernsen


1 Answers

You're probably want to achieve grid-like behavior, it can be easily achieved without JavaScript using flexbox:

  /* Purely for visual appearance */
.parent {
  width: 300px;  
}
.child {
  background: linear-gradient(45deg, lightgreen, yellow);
  padding: 5px;
  box-sizing: border-box;
}
/* Actual logic */
.parent {
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
}
.child {
  flex: 1 1 50%;
}
<div class='parent'>
  <div class='child'>a bit of text</div>
  <div class='child'>very large amount of content to make height largest across all rows</div>
  <div class='child'>a b c d e f g h i j k l m n o p q r s t u v w x y z</div>
  <div class='child'>a b c</div>
</div>
like image 56
Flying Avatar answered May 20 '26 09:05

Flying



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!