Home > OS >  CSS How to rotate image without less than 1 pixel gap
CSS How to rotate image without less than 1 pixel gap

Time:07-09

I'm am trying to make a grid of tiles that can be rotated in different directions. However, when I use transform to rotate them, a gap of less than a pixel is between them at certain resolutions. This code snippet shows this at certain resolutions:

div {
    transform: rotate(90deg);
    display: block;
    width: 10vw;
    height: 10vw;
    background-image: url("https://picsum.photos/seed/b/50");
    background-size: cover;
}
<div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div>

Is their any way to rotate images without this gap?

CodePudding user response:

I think (this is simply my guess after playing with your example a bit) what's happening here is that in those resolutions when you select a size like 10vw the size ends up with a fraction like 127.6 and the browser is not consistent with rounding it when you transform it.

CodePudding user response:

You seem to be seeing a part CSS pixel gap which occurs when the browser has to map a fraction of a CSS pixel into screen pixels. This is because on modern high res screens there are several screen pixels to one CSS pixel and sometimes a screen pixel can get 'left behind' in the calculations.

It's similar to a rounding error.

In this specific case of rotation a simple if hacky way of making things look better would be to scale the image very slightly after the rotation so it covers up the gap.

div {
    transform: rotate(90deg) scale(1.02);
    display: block;
    width: 10vw;
    height: 10vw;
    background-image: url("https://picsum.photos/seed/b/50");
    background-size: cover;
}
<div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div>

Of course there is the danger that this causes some knock-on problem somewhere else.

For similar problems but with gaps between background color and say the border of a div it is possible to add a pseudo element background which is slightly bigger to ensure any gap is covered.

  • Related