Search code examples
cssfrontendstyling

How do I disable sub-pixel rendering or force the browser to round properties to the nearest pixel?


My problem as stated in the title is about chrome's sub-pixel rendering. Sometimes you want the browser to determine an element's proper height or width so it takes up all the available space. And that's how floating point values appear. When the numbers after the decimal are high, it seems to get imprecise and make weird spacings. Changing the box-border property doesn't change the result. I made a codepen showing the problem, make sure to use a browser supporting sub-pixel rendering. As you zoom in you can see a space between the border and the pseudo-element.

* {
  box-sizing: border-box;
}

div {
  position: relative;
  
  width: 100.98px;
  height: 100px;
  
  margin-left: 2px;
  
  background-color: aqua;
  border-radius: 10px;
  border: solid 1px #000;
}

div:after {
  position: absolute;
  content:'';
  
  width: 15px;
  height: 100%;
  
  right: 0;
  
  background-color: black;
}
<div>


Solution

  • Turns out that rounding the width and height doesn't solve the problem at all; it's not about the float values (could be a factor). After some experimenting I found a trick of sorts. If you somehow manage to throw in a right: -1px or a left: -1px to the element's style it will no longer get weirdly spaced out (right: 0 or 1 doesn't work). I tested it with a resizable element. You can move it back into it's original position with transform: translateX(-1px) and there it is. No more subpixel gaps between elements. I made a codepen showcasing the solution: https://codepen.io/m4tex-the-sasster/pen/zYaMdwv