I am creating a mega menu trying to keep to current standards; CSS, jquery, bootstrap.
My menu is for product categories, which I want dynamically created in columns newspaper style. Easy enough, I have that working nicely. It requires a fixed height, which makes it overflow horizontally.
My current thinking is to, onload, increase the heights of each sub menu until there is no horizontal overflow. I can get it working with some manual intervention, which defeats to purpose of a dynamic layout.
.container {
width: 800px;
height: 100px;
display: flex;
flex: 1 1 auto;
}
.container .wrap {
display: flex;
flex: 1 1 auto;
flex-flow: column wrap;
align-content: flex-start;
}
.container .wrap .item {
width: 150px;
}
<div class="container">
<div class="wrap">
<div class="item">Item 1<br>a<br>b</div>
<div class="item">Item 2<br>a</div>
<div class="item">Item 3<br>a<br>b<br>c<br>d</div>
<div class="item">Item 4<br>a</div>
<div class="item">Item 5<br>a</div>
</div>
</div>
This style works perfectly aligning items top to bottom, left to right, as required.
Now I am trying to increase the height of each sub menu as required. Best solution is to detect width overflow and increase height to compensate.
I've tried native JS and jQuery, I seem to be getting stuck running it in a function. I can detect overflow and increase height, as my code below. What I want is to have the if statements in a loop and exit when no more overflow, and end up with a perfect fit.
EDIT Current working solution
$(function () {
$(".container").each( function( index, element ){
var my_height = $(element).outerHeight();
if( $(element).prop('scrollWidth') > $(element).outerWidth() ) {
while( $(element).prop('scrollWidth') > $(element).outerWidth() )
{
my_height += 100;
$(element).css('height', my_height + "px");
}
}
});
});
Works exactly as intended.
EDIT
Updated question. Is there a better solution? Something that doesn't involve looping over every item every page. Pure CSS would be nice, but don't think it's possible just yet.
Solved my transition issue. When trying to update the height in a loop as above, transition CSS interferes and creates an infinite loop. Was an easy fix, I added a new class to .container .transition and added $(element).removeClass("transition");
to the start or the loop and $(element).addClass("transition");
to the end. This removes the transition CSS from the inner loop and adds it back at the end.
FINAL EDIT
My first attempt was using css columns, but I couldn't get it working to my spec. It wasn't until reading the accepted answer below I revisited columns and after some testing got it working.
Ref https://developer.mozilla.org/en-US/docs/Web/CSS/columns