Thursday, May 12, 2016

A Tale of CSS and Sass Precision

[caption id="attachment_129763" align="aligncenter" width="800"]Various browsers as totems looking at a mysterious percentage sign Artwork by SitePoint/Natalia Balska[/caption]

At Edenspiekermann, we rely heavily on code reviews to make sure the work we commit is good enough™. One thing I regularly come across is the fuzziness around numbers, especially the ones that have a decimal point. Hence, here is a short article to shed light on this matter.

Initial Setup

To make the whole explanation clearer before even getting started, we are going to work on a small piece of code that happens to be very relevant to our case.

.list-item {
  float: left;
  width: 33%;
}

What’s the Problem?

Maybe you are wondering what the problem is with this code snippet. In appearance, not much. It is a three-column grid layout. Quite the usual you could say.

Although, 33% + 33% + 33% equals 99%, not 100%. While it might not make any difference in most cases, when working on straight alignments — 1% can make a big difference. 1% of a 1400px large container is 14px. That’s a pretty big distance.

Why don’t we just move the decimal dot (or rather add it) to make it more precise? We could probably reduce the gap to 1.4px, or even 0.14px which is not worth bothering anymore I suppose! Let’s start with that then.

.list-item {
  float: left;
  width: 33.33%;
}

That works better but it still ain’t perfect. This problem has been extensively discussed in this absolutely great article from John Albin Wilkins entitled “Responsive Design’s Dirty Little Secret”. If you haven’t read it, read it.

Can't the Browser Handle This?

At this point, you might be wondering why the browser cannot just make it work™. The thing is, the CSS specifications don’t specify (of the irony) anything to browser vendors about what to do in case of floating precision with percentage numbers. And when the CSS specifications omit a detail, you can be sure that every browser will do it its own way.

Take this example from the aforementioned article:

[…] with a 6 column grid, each column is 100% ÷ 6 = 16.666667% wide. On a 1000 pixel wide viewport (which I’ve conveniently picked to make our math easier), that calculates to 166.66667 pixels per column. Since the spec gives no guidelines, browser vendors are free to make their own rules. If a browser were to round to the nearest pixel, in our example, we’d arrive at 167 pixels. But since 167 x 6 = 1002 pixels, we’d no longer have room for all 6 columns in our viewport. Alternatively, if a browser rounded down to 166 pixels per column, we’d be 4 pixels short of perfectly fitting all columns into our viewport.
John Albin Wilkins

Continue reading %A Tale of CSS and Sass Precision%


by Hugo Giraudel via SitePoint

No comments:

Post a Comment