Home >Web Front-end >CSS Tutorial >A Tale of CSS and Sass Precision

A Tale of CSS and Sass Precision

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-21 08:46:09610browse

Challenges of percentage layout: Browser differences and floating point precision issues

Percentage layout is extremely challenging due to browser inconsistency and lack of specification of floating point precision, which can lead to render alignment and precision issues.

Advantages of Sass: Improve accuracy and code readability

Sass is a preprocessor scripting language that improves precision by handling complex calculations and makes stylesheets easier to read and update. However, Sass' default precision option is 5, which may still be too low for some cases.

calc() Function: Browser Calculation and Rounding

calc(..) CSS functions allow browsers to process calculations and rounding, potentially producing better results. This function, combined with Sass operation, provides the best of both worlds for CSS precision.

A Tale of CSS and Sass Precision

At Edenspiekermann, we rely on code review to make sure that the work we submit is good enough™. One thing I often encounter is the ambiguity around numbers (especially numbers with decimal points). So, this is a short article that aims to clarify this issue.

Initial Settings

To make the whole explanation clearer before we start, we will work on a small piece of code, which is very relevant to our case.

<code>.list-item {
  float: left;
  width: 33%;
}</code>

What is the problem?

You may be wondering what's wrong with this code. From the appearance, there is no big problem. This is a three-column grid layout, which is quite common.

However, 33% 33% equals 99%, not 100%. While this may not make any difference in most cases, when dealing with straight line alignment – ​​1% can have a big impact. 1% of a container that is 14 pixels wide is 14 pixels. This is a considerable distance.

Why can't we just move the decimal point (or add it) to make it more precise? We might reduce the gap to 1.4 pixels or even 0.14 pixels, which I guess is no longer worth the trouble! Then start here.

<code>.list-item {
  float: left;
  width: 33.33%;
}</code>

It works better, but still not perfect. John Albin Wilkins discusses this issue extensively in this article titled “The Dirty Little Secret of Responsive Design.” If you haven't read it yet, read it.

Can't the browser handle this?

At this point, you may be wondering why the browser can't make it work™. The problem is that the CSS specification does not (ironically) specify to browser vendors what to do with floating point precision for percentage numbers. When the CSS specification omits details, you can be sure that each browser will handle it in its own way.

The following examples from the above article:

[…] Use a 6-column grid with 100% width per column ÷ 6 = 16.666667%. In a viewport that is 1000 pixels wide (I conveniently selected it to make our math easier), each column computes to 166.66667 pixels. Since the specification does not provide guidelines, browser manufacturers are free to formulate their own rules. If the browser rounds to the closest pixel, in our example we will get 167 pixels. But since 167 x 6 = 1002 pixels, we no longer have room to accommodate all 6 columns in our viewport. Or, if the browser rounds down to 166 pixels per column, we will be 4 pixels less than perfectly putting all columns into our viewport. ——John Albin Wilkins

This is what happened. Older versions of Internet Explorer (mainly 6 and 7) rounded to the nearest integer, causing layout interruptions. WebKit browser rounds down, which prevents any catastrophic layout results, but leaves us with extra space. Opera (at least in its old rendering engine) does something weird that I'm too lazy to explain. However, there are no rules for this behavior in the specification, so who should I blame? Of course not those browsers that use subpixel rendering, because ultimately this is the way to produce the best results.

Anyway, this is simply a mess and we will discuss this issue again in the conclusion of this article.

How about Sass?

Sass supports mathematical operations. This is nothing new, it is actually one of several things Sass initially used (for building a math-based grid system). We can tell Sass that we want to divide the width of the container into 3 equal parts.

<code>.list-item {
  float: left;
  width: 33%;
}</code>

We can also use percentage(..) function to get the same result:

<code>.list-item {
  float: left;
  width: 33.33%;
}</code>

In Ruby and LibSass, the accuracy option for Sass is 5. This is actually a problem because it's very low; 10 would be better, but that's not the default (although configurable, but not very easy).

This code will generate the following CSS:

<code>.list-item {
  float: left;
  width: (100% / 3);
}</code>

This doesn't solve our browser problem, but it does make writing stylesheets easier. Not only do we not have to deal with the calculations and precision ourselves, we also make the code easier to read and update by actually displaying the calculations.

I think this is a good thing.

The best of both worlds

So far, we have learned that it is better to let Sass handle the calculations for us rather than hardcode the values. Now, the best way is to let the browser handle this in the best way it can. To do this, the calc(..) CSS function can be used.

<code>.list-item {
  float: left;
  width: percentage(1 / 3);
}</code>

This code will not compile into anything. It appears in the browser as authors write. The browser is then responsible for making the most of it. I'll tell you completely honestly that I'm not sure if the browser handles the calc(..) value as it does with regular values. I think they do the calculations and then round. Some browsers seem to incorporate subpixel rendering into the equation. If you have any insights on this, please share it in the comments.

For browsers that do not support calc(..) expressions (mainly Internet Explorer 8 and Opera Mini), we can place a static value represented as a Sass operation before it. In this way, we can have the best of both worlds.

<code>.list-item {
  float: left;
  width: 33%;
}</code>

Conclusion

Let's review quickly. First, percentage layout is difficult to deal with due to browser inconsistency and lack of specifications for floating point precision.

Then, hard-code values ​​produced by some complex calculation are not usually a good idea. We can have Sass calculate an approximation (5 decimal places).

Better yet, we can have the browser compute an approximation. In an ideal world, when the browser is responsible for math and rendering, it should be able to make the most of it. To move in this direction, we rely on the calc(..) function.

This is almost the current situation. Nothing new, but I think a quick review will help!

FAQs about CSS and Sass Accuracy (FAQ)

What is the difference between CSS and Sass?

CSS (Cascading Style Sheet) is a stylesheet language used to describe the appearance and formatting of documents written in HTML. Sass (smart stylesheets in syntax) is a preprocessor scripting language that is interpreted or compiled into CSS. The key difference between the two is that Sass has features that do not exist in CSS, such as variables, nesting, mixin, inheritance, etc. These features make Sass more powerful and flexible than CSS.

How does precision work in CSS and Sass?

The precision in CSS and Sass refers to the detail and accuracy of the style rendering. In CSS, precision is often limited due to the lack of variables and functions. Sass, on the other hand, allows for higher accuracy thanks to its advanced features. For example, you can define variables for a specific color or size and use them consistently throughout the stylesheet to ensure accuracy and consistency in your design.

Can I use Sass in any web project?

Yes, you can use Sass in any web project. Sass is compatible with all versions of CSS. So you can start with CSS and add the Sass feature as needed. However, remember that Sass requires a preprocessor to convert it into a CSS that the browser can interpret.

What are the benefits of using Sass over CSS?

Sass offers several benefits over CSS. It allows the use of variables, nesting, mixin and inheritance, which can make your stylesheet more organized, reusable, and easy to maintain. Sass also supports math operations, allowing you to calculate dimensions and colors directly in the style sheet.

How to improve the accuracy of CSS or Sass code?

You can improve the accuracy of your CSS or Sass code by using variables to obtain consistent values, using mathematical operations to perform precise calculations, and using functions and mixins to obtain reusable styles. Additionally, using CSS reset can help ensure consistency between different browsers.

What is a CSS preprocessor and why does Sass need it?

CSS Preprocessor is a scripting language that extends the default functionality of CSS. It allows you to use variables, nested rules, mixins, functions, and math operations in stylesheets. Sass is a CSS preprocessor. It is necessary because the browser can only interpret CSS. Therefore, the Sass code needs to be compiled into CSS before it is used in a web project.

How does Sass help write DRY (don't repeat yourself) code?

Sass supports features such as variables, mixin and inheritance, which helps write DRY code. A variable allows you to define a value at a time and use it in multiple places. Mixin allows you to write reusable styles that can be included in other rules. Inheritance allows you to share a set of CSS properties from one selector to another.

What are the potential pitfalls of using Sass?

While Sass offers many advantages, it also has potential pitfalls. The need for preprocessors may increase the complexity of the development process. Additionally, some Sass features such as nesting and mixin may cause CSS output to bloat and inefficiency if used improperly.

How to get started learning and using Sass?

There are many resources available to learn Sass online. The official Sass website provides a comprehensive guide to getting started. You can also find tutorials on web development websites and online learning platforms. To get started with Sass, you need to set up a Sass preprocessor in your development environment.

Can I convert my existing CSS code to Sass?

Yes, you can convert your existing CSS code to Sass. Since Sass is a superset of CSS, any valid CSS is valid Sass. You can first rename your .css file to .scss (Sassy CSS), and then gradually start using the Sass feature in your code.

The above is the detailed content of A Tale of CSS and Sass Precision. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn