manny999 manny999 - 2 months ago 13
CSS Question

Equal heights & media queries

I am puzzled with an equal height problem I am having, you can see in this Fiddle: FIDDLE

Code:

$(document).ready(function() {
if ($(window).width() > 768) {
$(window).ready(function() {
var mainHeight = $('.main').height();
$(".block-wrap").height(mainHeight);
});
}else{
$('.block-wrap').css('height','auto');
}
});

$(document).ready(function() {
if ($(window).width() > 768) {
$(window).resize(function() {
var mainHeight = $('.main').height();
$(".block-wrap").height(mainHeight);
});
}else{
$('.block-wrap').css('height','auto');
}
});


Basically I want the 'block-wrap' to get the height of 'main' div. It works until I use a media query.. the 'block-wrap' still get the height from the 'main' div, while I would like to set it's height on auto, as I tried in the javascript.

It works under 768px if I refresh the page, not on resize.

Answer

Well, your JavaScript code has numerous problems, including the fact that it was typed twice (?). Here's what I've changed:

  • Removed the duplicate.

  • Wrapped everything in a single $(document).on("ready", callback); event handler.

  • Added a resize event listener in order to update your .block-wrap div height whenever the user resizes the screen. Without it, the height would only change when the page was loaded, but not if the user changes the window size.

UPDATE:

  • Called the resize(); function after the resize event handler to resize the .block-wrap div after loading the page.

Note that you can achieve this result without relying on JavaScript, by using CSS instead.

Here's the final code, optimized and working:

$(document).ready(function () {
    function resize() {
        if (window.innerWidth >= 768) {
            var mainHeight = $('.main').height();
            $(".block-wrap").css({
                "height": mainHeight
            });
        } else {
            $('.block-wrap').css({
                'height': 'auto'
            });
        }
    }
    resize();
    $(window).on("resize", function () {
        resize();
    });
});

And I've adjusted your media query max-width condition by one pixel:

@media only screen and (max-width: 768px) { ... }

Demo: JSFiddle

Comments