Tomek Buszewski
Tomek Buszewski

Reputation: 7955

Percentages with SASS - one pixel problems?

I want to build my minimal CSS framework. I did a grid system in SASS:

$width: 960px;
width: $width;

.grid-12 { width: $width; }
.grid-11 { width: percentage((($width/12)*11)/$width) }
.grid-10 { width: percentage((($width/12)*10)/$width) }
.grid-9 { width: percentage((($width/12)*9)/$width) }
.grid-8 { width: percentage((($width/12)*8)/$width) }
.grid-7 { width: percentage((($width/12)*7)/$width) }
.grid-6 { width: percentage(($width/2)/$width) }
.grid-5 { width: percentage((($width/12)*5)/$width) }
.grid-4 { width: percentage(($width/3)/$width) }
.grid-3 { width: percentage(($width/4)/$width) }
.grid-2 { width: percentage(($width/6)/$width) }
.grid-1 { width: percentage(($width/12)/$width) }

It works great, but sometimes - in some resolutions, eg. at my mobile with landscape view (960x540) some elements are 1px too short. It happens also when I resize browser.

What can I do?

Upvotes: 0

Views: 210

Answers (2)

Miriam Suzanne
Miriam Suzanne

Reputation: 14020

There is no "fix" for this. That's the way it is with all responsive layouts and grid systems. There are techniques like float isolation that can help keep your rounding errors from multiplying. Otherwise, 10 1px errors can turn into a 10px error. I wouldn't use that everywhere, but it's useful if you have a gallery-style layout with a lot of elements, all the same size, floating next to each other.

The real solution, mentioned in a comment above, is to adjust your design so that 1px rounding errors don't matter. If 1px can ruin your layout, responsive design isn't going to work.

You can't eliminate the rounding errors, but you have some control over where the missing pixels should go. By floating things left or right, and nesting in different ways, you can move the rounding errors where they will be least noticeable. Another solution is to apply layout (instead of float/width) to the last element in a row, and it will expand to fill the remaining space. The easiest way to apply layout is with overflow: hidden;, but that has some drawbacks.

Upvotes: 2

Mihnea Belcin
Mihnea Belcin

Reputation: 554

some of the calculations will result in a number that can NOT be divided by 2

sometimes you will get .5px ...

and because of this . you will sometimes have 1 extra pixel

Upvotes: 3

Related Questions