0

Alright guys, I've got a problem / question and I can't find an answer to it. So let's say I've got something like this:

<div className='container'>
    <div className='wrapper' style={{
        width: 40,
        height: 40,
        backgroundColor: 'red'
    }}>
        <div
            className='item'
            style={{
                width: 18,
                height: 18,
                backgroundColor: 'black',
            }}
        />
    </div>
</div>

So basically I've got a square with a square inside it within a top container.

If I add padding to the container the size and position of the item will change:

enter image description here

As you can see the size of the item is changing [IN THE VIDEO I CHANGING THE PADDING ON THE CONTAINER] (if it's would be positioned to center then the position would change too..., as the Chrome's inspector says it's remains at 18px)

P.S.: If the item's size is an even percentage (or px) like 10%, 20%, 30% ... 90%, so on then the size and the position won't change. (Same if I use PX and it's equals = 10% ... 90%.. eg.: 4px, 8px, 12px...)

Istvan Orban
  • 1,607
  • 3
  • 18
  • 34
  • here is a similar problem : https://stackoverflow.com/questions/48044040/transform-scale-works-incorrectly-for-odd-pixel-widths/48048934#48048934 ... it's due to browser rendring and some subpixel calculation – Temani Afif Aug 16 '18 at 21:51
  • Hmm yeah this one really looks similar. It's really strange :(. In my real application this is an Item which got a Wrapper with an Icon in it. (Item->Wrapper->Icon) but my icon(font icon) won't be centered if it's size not an even 10% percentage (what seems a little strict rule. :/) – Istvan Orban Aug 16 '18 at 21:59

1 Answers1

1

This happens due to sub-pixel rendering combined with the way a CSS pixel is rendered.

From the article linked:

... A CSS ‘px’ unit (because it is 1/96 of an inch) may resolve to a fractional number of device pixels. For example, on a 300dppi (device pixel per inch) screen the ratio of device pixels to CSS pixels pixels is 300/96 = 3.125.

Basically, when your elements are positioned at very specific spots on your screen, the browser renders them with the dimensions you specified, but they may appear to bleed one pixel over or fall one pixel back due to your monitor's odd CSS-pixel-to-screen-pixel ratio.

If you were to try your same test using a different screen, the elements would have the same "problem" but likely at different spots on the screen.

Adam
  • 3,829
  • 1
  • 21
  • 31