Skip to content Skip to sidebar Skip to footer

Round Div Height To The Nearest Even Number If It Has An Odd Value

Basically I want to use transformY but the subpixel blur is very annoying and only occurs when the div is an odd height. As the height depends on the text viewport etc, need this t

Solution 1:

The question is old, but it's the first answer on google for "rounding div height to even number", so it might help others.

You have perfectly identified the issue: translates can cause blur due to result not being rounded to the nearest pixels, so rounding the div height to an even number fixes it.

We can't do it in CSS as it doesn't know yet its final height, so we have to do it after rendering. Using Jquery is a breeze:

$(window).on("load", function() {
    $('div').each(function (index, value) {
        if($(this).height()%2==1) $(this).height( 2*Math.round($(this).height()/2 ) ) ;
    });
});

(of course, same could be done in VanillaJS, with a few lines more)

Explanations

  • $(window).on("load") event is important here, as the final height will be known after final rendering, including image dimensions, that are still unknown when DOM is loaded
  • height %2 ==1 uses modulo operator to check if there's a remainder when dividing by 2 -> odd

  • Then, as you said, rounding it to nearest (upper) even pixel using 2*(round(height/2))

jsFiddle to demonstrate the blur and the fix

Post a Comment for "Round Div Height To The Nearest Even Number If It Has An Odd Value"