Decimal places in CSS percentage - css

OK, I've searched far and wide and come up with nothing more than anecdotal evidence to suggest that there is no recommended standard behaviour in the CSS specification for the precision of floating point numbers.
N.B. I'm not asking about the well known sub-pixel rounding problem.
The reason I'm asking is that IE seems to round percentage-based floating point values down to 2 decimal places, whereas Webkit and Gecko allow at least 3, or even more (I haven't tested).
For example:
li {
width: 14.768%;
}
When inspected in Chrome's Web Inspector or Firebug, the <li>s are correctly shown to have a width of 14.768%. However, in IE dev tools (IE9/8/7 mode), they have a width of 14.76%. This causes the actual pixel-based values to be completely out as well.
Can anyone shed any light on this behaviour, or provide a suitable workaround? I'd rather not have to resort to pixel-based values if possible, as the content needs to be fluid width.
I know it's pretty gnarly dealing with this many decimal places, but I'd be very interested to know which, if any, of these browsers is "correct"?
EDIT
Firefox seems to use the correct percentage values when shown in the inspector (not rounded to 2 decimal places), but is displaying the same behaviour as IE in terms of actual pixel placement.

There are probably many solutions for your problem, I would suggest these:
Round on 2 decimals by yourself for all but one, than reduce from
total width for last one.
Use table or display: table, than the
browser will fix the widths by itself.

For anyone coming upon this question, this article goes into depth about what different browsers do for percentages with decimal points: https://cruft.io/posts/percentage-calculations-in-ie/
As for which browser is correct, according to that article:
The HTML5 Specification doesn’t mention truncating or rounding decimal
places. Point 11 deals with decimal places, and says to keep looping
until “position is past the end of input, then return value as a
length”.

Related

Are sub-pixel line-height values ignored by Chrome?

I'm using Electron to try to make a native app. The interface has an image of a scanned document as a div background image, with the OCRed text as content. I'm able to match almost all the styles of the scanned document (to a degree that satisfies me, anyway), but line-height is problematic.
The correct size of the font seems to be 10.5pt. When the line-height is set 100%, the content text is a little too high and the text drifts beyond the scan. Set at 99%, it's too small... and 99.5% doesn't seem to make any difference in rendering. This isn't a problem with using percentage values either, as I find the same thing occurs whether I use pixel values, em, or whatever. There are values that cause different rendering, and any fractional values between those are ignored.
If I use the magnification/zoom on this (control-+), fractional values start working, but fail once I've unzoomed.
Are these values being ignored by Chrome, or is it something else which causes this behavior (my montior's dpi, some aspect of font rendering in general I'm dumb and don't understand, etc)?
Is there a work-around for this? I don't need pixel perfect matching on this, but the difference amounts to about 3 lines worth of text, which isn't close enough for my purposes.

How do browsers deal with non-integer values for height and width?

When browsers are given widths and heights for elements that aren't integer values, how do they deal with them?
In particular,
At what stage do non-integer values get rounded? Do they round to the nearest integer, or truncate them?
When a container's children have non-integer dimensions, will there ever be instances where the sum of the child lengths or heights not equal the inner width / height of the parent element?
Do provided non-integer dimensions get handled differently to non-integer results of percentage-based dimensions?
What about non-whole values for padding and margins?
Edit: Is it the browsers that perform this rounding, or is it the OS? If it's the OS, does that create conditions where the browser 'thinks' items are larger than their painted area, and does that create issues with the sizing of parent containers?
Assertion
Browsers are designed to deal with floating point numbers and values less than one pixel.
To see a simple example showing that browsers use floating point numbers in their calculations, create a 3% width item and look at its calculated properties in Chrome developer tools as it is resized.
You should see something like this:
"35.296875" can't be precisely rendered by a display that maps one pixel to one pixel in the physical display (CRT, traditional LCD). However, newer high density displays use a different ratio than 1-1 and this fractional value could conceptually be used to provide a greater degree of precision.
Even on low density displays, a fractional value could provide a hint for subpixel rendering, which uses the red, green and blue components of the pixel to make the edges of an object appear smoother than possible with whole pixel values.
But exactly what the browser will do with such numbers isn't very predictable. You can't (currently) ask a browser to make a box 31.5px wide and expect a consistent or even meaningful result. Some browsers will truncate fractional values; others round up/down.
Subpixel rendering is commonly used for text and works quite well in most/all browsers, but each browser implements this differently and there is very little a developer can do to impact how this works.
When
At what stage do non-integer values get rounded in the inheritance
chain?
Most/all calculations are performed as floating point numbers and any rounding may occur late in the process, or even outside of the browser's control. For example, a browser may delegate its anti-aliasing to an OS component (such as IE9 does to Windows Direct2D and DirectWrite).
CSS transitions may be tightly integrated with OS and/or hardware acceleration. This is another case in which I think it is highly likely the floating point values are preserved by the browser and passed to the underlying layer(s).
Rounding Behavior/Errors
When a container's children have non-integer dimensions, will there
ever be instances where the sum of the child lengths or heights not
equal the inner width / height of the parent element?
I've seen this in older browsers (IE7) as a result of percentage calculations, where 50% + 50% > 100%. Usually it is not a problem until you try to do something more complicated. Anecdotally, I have seen "off by one pixel" bugs when attempting to precisely align HTML elements as part of an animation.
Percentages vs. other Units
Do provided non-integer dimensions get handled differently to
non-integer results of percentage-based dimensions?
Do they round to the nearest integer, or truncate them?
It varies. This older answer states that they are truncated, but (in Chrome 24) I see rounding (note the example fiddle). Note my earlier comment about the differences between Chrome and Safari on the same machine.
What about non-whole values for padding and margins?
The same rules (or lack thereof) appear to apply.
Standards
I haven't found a standard definition for how floating point values should be handled in all cases. The closest relevant spec I can find talks about canvas pixels:
The handling of pixel rounding when the specified coordinates do not
exactly map to the device coordinate space is not defined by this
specification, except that the following must result in no visible
changes to the rendering: [...list of conditions...]
Again, this is from a section dealing specifically with canvas, but it does insinuate:
Browsers absolutely interact with fractional pixels.
Actual implementations will vary.
Some standardization does exist.
Mapping to the device's display may factor into the calculation.

CSS: Why defining very long % values?

I have seen a few design where the developers have defined very long values in percentage. I am wondering what's the reason to write so long values, why not just round about? and how do you even calculate/convert such values?
For example (taken from a css file):
.thumbnail { width: 68.08510638297872%; }
table { font-size: 0.9166666666666667em; }
Most likely they are using some kind of CSS templating engine like Sass to generate stylesheets from code, and setting widths based percentage calculations.
In the book Responsive Web Design Ethan Marcotte actually advocates leaving all the numbers after the decimal place when calculating percentage-based widths, to give the greatest accuracy, even when the developer is calculating the widths themselves using a calculator.
EDIT: I just dug out my copy of the book, and here is Marcotte's reasoning:
Now, you might be tempted to round 0.45833333333333em to the nearest
sane-looking number—say, to 0.46em. But don’t touch that delete key!
It might make your eyes bleed to look at it, but 0.458333333333333
perfectly represents our desired font size in proportional terms.
What’s more, browsers are perfectly adept at rounding off those excess
decimal places as they internally convert the values to pixels. So
giving them more information, not less, will net you a better result
in the end.
That looks to me like those figures are generated programatically, not by humans directly. No Scotsman would do such a thing. Well, no true Scotsman :-)
Probably they come from a WYSIWYG layout editor that couldn't care less about readability, never expecting anyone to go and hand-edit the output.
The most clients want a pixel perfect website inside the browser with scalabel font-size and web-content.
The developer has used the long percent, to get it perfect matched to the layouts.
Percent and em is an scalable unit not an pixel related unit and on some resolutions or font-size scales, the element do not match with the layouts and you can make it precise with more decimal places.
Newer Browser like Chrome or Firefox scale the font and the elements at once and this problem will not happen, but older browsers like ie 6-7 hasn't this feature and must learn it with em or percent units.
I hope it will help you to understand this problem

Chrome, CSS - zoom sensitive layout

Setup:
I have a simple box with rounded corners, that has a header and expands according to the amount of text, as discussed in Dan Cederholm's Bullet Proof Web Design (ISBN 0-321-34693-9).
Works great, EXCEPT when zooming in Google Chrome. Then the right margin of the box disappears.
It works in IE and FireFox without problems.
Example:
Example in jsFiddle
In chrome, it fails at zoom 110% and other zooms too. No problems in IE or FireFox.
Questions:
Any ideas what is causing this?
In general, what makes layouts zoom-sensitive (if any such general rule exists...)?
Is Dan Cederholm's book really bullet proof...?
How far back do you need to be compatible?
I mean, if you can drop IE7/8 you should be using css3 rounded corners. If you need to support IE8/7 you should definitely considder using graceful degradation in this case. It is probably not worth the time and effort to strive for perfection everywhere. That is simply a goal which cannot be met when browsers will never get updated again.
1) What may be causing this
That is a fairly broad question, I couldn't reproduce the problem, or really find one in Chrome 20 (beta) so I will just list a things that can mess it up.
General browser rounding errors, browsers aren't precise, weren't designed to be precise sub-pixel
Mixing px values with other values, different roudings make values add up differently..
Positioning of in-flow elements which get influenced by other in-flow elements on the page (these are hard to track down usually)
Parent element properties (parents with overflow hidden, fixed sizes, for example, I think this might be the problem here in the jsfiddle)
Bugs in browsers
Combination of the above
In this case jsfiddle has a crapload of containers and frames (with overflows set to hidden, fixed heights/widths, px based) etc on the page, even in 'full screen' view. So if you really want to make sure, make a html file on your own pc open/test with that.
2) In general, what makes layouts zoom-sensitive (if any such general rule exists...)?
In todays browsers this may not be all that relevant because zoom functionality is often very advanced and can even scale full-px based layouts without much problems. The only real problem browser which is still used today is IE7. The zoom capability of IE7 is atrocious, and for that reason you should only use % or em based values for text.
The only 'official' related guidelines can be found in WCAG 2.0, the w3 accessibility guidelines/techniques writeup:
http://www.w3.org/TR/WCAG20-TECHS/G142.html
So browsers can scale, modern ones have no problem here, but weren't designed to be accurate, it's also an impossible task with mixed units (em, %, px).
3) Is Dan Cederholm's book really bullet proof...?
Before I start here, I haven't read the book... I never read a CSS book (plenty other resources) in my life, but my first and foremost skill is dreaming it.
Let's start with "What is bulletproof?". Bulletproof in web-design means it will work, everywhere, and will not break, anywhere. This alone should give you a clue.
It might have very well been bulletproof when he wrote that book, but the web is a dynamic place, and even if I take the latest announcement blogpost for the book it dates from December last year. Since then at least 3 new Chrome versions came out (rough estimation) and even more Firefox versions. Microsoft sat on his ass that this time (we would've been in big trouble if they decided to do rapid release schedules).
Things changed, new bugs have definitely been introduced since then.
Regardless of what is breaking it, nothing is ever bullet proof, just very, very close to what you want to always happen, with slight variations between browsers.
That doesn't mean it is a terrible book, looking at his CV he's definitely and a guru on web-design, so he's probably right about a lot of things in that field. I just hope he explains why things are done in a certain way, because that makes you a lot wiser than just learning to do things.
A: "You always use EMs for text! EMs are annoying! Why do you do that anyway?!"
B: "I dunno, read somewhere I should..."
A: "Lets just use pixels! Pixels always work."
B: "Hmmm ok."
You just lost IE7 support. (whether that's a bad thing, is another discussion)
First of all, you're using a background-image, something I would have loved you to have mentioned.
1) So yah, as mentioned in the comments below your post, it's just rounding errors of the div, which crops the background-image.
2) I have no sources sadly, but in my experience, objects using text as a measurement are zoom-sensitive, pictures sometimes not zooming relative to everything else, and content with a predetermined 'set' size (such as textareas, radios buttons, etc).
3) Nothing is bullet proof, especially with something as ever-changing as the web that also behaves differently on different browsers. Hazards of the trade.

Font size in CSS - % or em? [duplicate]

This question already has answers here:
What is the difference between px, em and ex?
(4 answers)
Closed 1 year ago.
When setting the size of fonts in CSS, should I be using a percent value (%) or em? Can you explain the advantage?
There's a really good article on web typography on A List Apart.
Their conclusion:
Sizing text and line-height in ems,
with a percentage specified on the
body (and an optional caveat for
Safari 2), was shown to provide
accurate, resizable text across all
browsers in common use today. This is
a technique you can put in your kit
bag and use as a best practice for
sizing text in CSS that satisfies both
designers and readers.
Both adjust the font-size relative to what it was. 1.5em is the same as 150%. The only advantage seems to be readability, choose whichever you are most comfortable with.
From http://archivist.incutio.com/viewlist/css-discuss/1408
%: Some browsers doesn't handle
percent for font-size but interprets
150% as 150px. (Some NN4 versions,
for instance.) IE also has problems
with percent on nested elements. It
seems IE uses percent relative to
viewport instead of relative to
parent element. Yet another problem
(though correct according to the W3C
specs), in Moz/Ns6, you can't use
percent relative to elements with no
specified height/width.
em: Sometimes browsers use the wrong
reference size, but of the relative
units it's the one with least
problems. You might find it
interpreted as px sometimes though.
pt: Differs greatly between
resolutions, and should not be used
for display. It's quite safe for
print use though.
px: The only reliable absolute unit on
screen. It might be wrongly
interpreted in print though, as one
point usually consist of several
pixels, and thus everything becomes
ridiculously small.
The real difference comes apparent when you use it not for font-sizes. Setting a padding of 1em is not the same as 100%. em is always relative to the font-size. But % might be relative to font-size, width, height and probably some other things I don't know about.
Given that (nearly?) all browsers now resize the page as a whole, rather than just the text, previous issues with px vs. % vs. ems in terms of accessible font resizing are rather moot.
So, the answer is that it probably doesn't matter. Use whatever works for you.
% is nice because it allows for relative resizing.
px is nice because it's fairly easy to manage expectations when using it.
em can be useful when also used for layout elements as it can allow for proportional sizing related to the text size.
As Galwegian mentions, px is the most reliable for web typography, as everything else you do on the page is mostly laid out in reference to a computer monitor. The problem with absolute sizes is that some browsers (IE) won't scale pixel-value elements on a web-page, so when you try to zoom in/out, everything adjusts except for those elements.
I do not know whether IE8 handles this properly, but all other browser vendors handle pixels just fine and it is still a minority case where a user needs to enlarge/diminish text (this text box on SO perhaps being the exception). If you want to get really dirty, you could always add a javascript function for making your text size larger and offer a "small"/"larger" button to the user.
Regarding the difference between the css units % and em.
As far as I understand (at least theoretically/conceptually, but possibly not how these two units might be implemented in browsers) these two units are equivalent, i.e. if you multiply your em value with 100 and then replace em with % it should be the same thing ?
If there actually is some real difference between em and % then can someone explain it (or provide a link to an explanation) ?
(I wanted to add this comment of mine where it would belong, i.e. indented just below the answer by "Liam, answered Sep 25 '08 at 11:21" since I also want to know why his answer was downvoted, but I could not figure out how to put my comment there and therefore had to write this "thread global" reply)
Yahoo User Interface library (http://developer.yahoo.com/yui/) has a nice set of base css classes used to "reset" the browser specific settings so that the basis for displaying the site is same for all (supported) browsers.
With YUI one is supposed to use percentages.

Resources