Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent margin with em

Tags:

html

css

I'm using an em-based margin for homogeneous (in terms of markup, class, id, etc.) items in a menu. As far as I can tell, the margins for each of these items should be rendered identically. However, some are being rendered as 1px, and some as 2px. There may be some pattern to this (e.g. every second item is rendered as 2px), but not that I can discern.

I've observed this behavior in both Firefox and Chrome, on Linux and OS X.

I'm guessing this is due to the calculated value of each these margins being a decimal number (1.6px according to chrome devtools), but why isn't the same decimal number being rendered consistently?

There's a codepen example below, and I'm also including an enlargement of a screenshot demonstrating the issue.

http://codepen.io/anon/pen/KoAbl

like image 945
ebenpack Avatar asked Oct 01 '22 11:10

ebenpack


2 Answers

I'm just speculating, this is just a guess, but what if it does round it to the nearest whole pixel (1.6 => 2), but then accounts for that rounding in the next padding. Since the padding was 0.4 pixels too much last time, it'll be 1.6 - 0.4 = 1.2 pixels next time, which rounds to 1 pixel.

The next one will be 1.6 + 0.2, which is 1.8, and rounds to 2. Next will be 1.6-0.2 = 1.4, rounded down to 1. Next will be 1.6 + 0.4 = 2, and from that the pattern repeats itself again.

This would mean the paddings are 2px, 1px, 2px, 1px, 2px (repeat) 2px, 1px, 2px, 1px, 2px, which seems to me be the same paddings that you actually have.

like image 186
Erik Lumme Avatar answered Oct 30 '22 05:10

Erik Lumme


I cant tell you exactly how em's are calculated. But I can tell you its probably due to a rounding of the font-size. You change the font-size to 10px or 20px and the inconsistency goes away. Change it to 15px and the problem comes back.

See this post: CSS: Em rounding error

like image 44
tgeery Avatar answered Oct 30 '22 07:10

tgeery