Search code examples
htmlcsscss-position

Abnormal/unwanted margin in HTML page


I have this small block of html which is showing some funny behaviour.

<div style="position:relative; width:100px; height:25px; border:2px solid grey; background: rgb(205, 234, 238);">
   <div style="position:absolute; left:0; top:0; width:80%; height:100%; background: rgb(9, 201, 95);"> 
   </div>
</div>

enter image description here

You can see the small margin to the left and bottom sides of the inner green box. As it is clear from the code, I have set left as 0 and height as 100%. I am aware of reset styles and I am using the below simple CSS

*{ border:0;padding:0;margin:0;outline:0;box-sizing: border-box;font-family: roboto;} 

I also tried out the block of code in W3schools online editor just to double check the output and the issue persists. Another funny behaviour is that sometimes when I experiment with the CSS, a gap appears on the top of the green box and the gap at the bottom disappear.

Any idea what is happening here?

Update after some testing based on answers

Chrome 90.0
I verified that zoom levels were all normal. I tried changing zoom level and the gap disappears at 50%, 80%, 125%, 175%, 200% etc but in normal view the issue persist.

Edge 88.0
Exact same behaviour as chrome (gap disappears at exact same zoom levels)

Firefox 88.0
I just ran the code in firefox and the problem does not show up there. Even if I change the zoom level there are no issues in firefox

So it seems like the issue occurs in Chrome and edge.
Any solution to this problem?


Solution

  • This is not specifically to do with zooming, though the phenomenon can become apparent at different zoom levels.

    The problem is the arithmetic the system is having to do on percentages and pxs and what to do when there is the potential for rounding. A CSS pixel is often rendered as a multiple of pixels on modern, high def, displays so when it's faced with a part pixel it can leave behind a display pixel.

    One workaround in the case given in the question is to put the backgrounds all in the parent element (as linear gradients):

    <div style="position:relative; width:100px; height:25px; border:2px solid grey; background-image: linear-gradient(to right, rgb(9, 201, 95) 0%, rgb(9, 201, 95) 80%, rgb(205, 234, 238) 80%, rgb(205, 234, 238) 100%)">
      <div style=" width: 80%; height: 100%;">
      </div>
    </div>