Round div height to the nearest even number if it has an odd value

天大地大妈咪最大 提交于 2021-02-05 08:47:08

问题


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 to be flexible so realistically need it to get the height of the div - Divide it by 2, round to the nearest number then x 2 so it'd always produce an even value.


回答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



来源:https://stackoverflow.com/questions/29098087/round-div-height-to-the-nearest-even-number-if-it-has-an-odd-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!