Is it possible to “snap to pixel” after a CSS translate?

前端 未结 4 1808
谎友^
谎友^ 2021-02-01 15:15

I created a modal box and vertically centred it using a technique Chris Coyer mentioned. The only problem I\'ve found with it so far is that sometimes the box is offset by half

相关标签:
4条回答
  • 2021-02-01 15:56

    As I encountered same problem with subpixels in Chrome and in version 64 it still can't handle subpixel transform values , I decided to write small js script, that fixes subpixel problem. You can find it on github. It simply rounds transform value to full pixel.

    Hope someone will find it helpful!

    0 讨论(0)
  • 2021-02-01 15:57

    I always use perspective: 1px;, for example:

    {
      margin: 50% 0 0 50%;
      perspective: 1px;
     transform: translate(-50%, -50%);
    }
    
    0 讨论(0)
  • 2021-02-01 16:00

    The only bulletproof solution is to ensure that your element occupies an even number of pixels. If the height (or width) is not divisible by 2, then it will attempt to render your element on a half-pixel, causing the blurriness.

    Firefox doesn't have this issue because it supports true subpixel rendering. So, even though your element is on a half-pixel, Firefox handles it elegantly.

    In my experience, Webkit typically snaps elements to the nearest pixel –– (for instance, when using the letter-spacing property) -- so it's kinda strange that it doesn't behave the same way for translate.

    0 讨论(0)
  • 2021-02-01 16:03

    In some browsers you can avoid 3d transforms and use 2d transforms instead, the translation will snap to pixels by default:

    transform: translate(-50%, -50%);
    

    rendering is snapped to pixels

    transform: translate3d(-50%, -50%, 0);
    

    rendering is anti-aliased

    JSBin: http://jsbin.com/epijal/3/edit

    0 讨论(0)
提交回复
热议问题