Skip to main content

Cross-browser behaviours: fractional pixels

When manipulating CSS values directly, be careful of how precise your numbers are, as different browsers treat decimal values for pixel sizes differently.

For instance:

image.png

Here is an image overlaid by a gray "filtered" rectangle, residing within a container that is 689.406 pixels wide. If you look carefully at the right edge of the gray area, you'll see that a small sliver of the image is visible, because the gray rectangle is not fully covering the image, due to a decimal rounding error.

 JavaScript will report the width of the container correctly, but Chrome on the other hand will not:

image.png

Unfortunately, the 689.41 rounding is not just for debugging purposes; the element has been displayed at that size. In this case, the gray rectangle has been put in this wide container, and given a left css attribute to align it with the image inside - but because the width of the container is not accurately reported, the left attribute is slightly smaller than it needs to be, resulting in the small visible sliver of the image on the right.

Fixing this bug requires rounding the necessary numbers to 2 decimal places to ensure the calculation will line up with what Chrome actually displays:

let mainImageContainerWidth = $(`#${prefix}gallery-image-content-container-${id}`).width();

// THIS IS 2024! IT SHOULDN'T BE NECESSARY!
mainImageContainerWidth = mainImageContainerWidth.toFixed(2);

Be careful this doesn't cause issues on browsers such as Firefox, which do show fractional pixels to higher precision, as you might end up with elements being slightly bigger than expected.