This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Evenly distributed height of child elements with CSS
Lets say i have a design with 6 DIVs that are float left with a width of 16.666%.
So the document size is splited in 6 parts.
Now if i have a document size of lets say 620px wide this would make each part 103.333px. Since i don't know screens that can show partial pixels :) I wonder how the browser handles the partial pixels.
Here is my testcase:
http://jsfiddle.net/dhQh2/ (Just resize the window to get a result)
When resizing it seams that the 6 DIVs keep the same size. But it some cases it can't be. How does the browser handle those partial PX values?
If, for example, you're using a % width, and the exact width should be 103.333px, then the browser must make a decision on how display that.
Different browsers make different decisions, read these links for more information:
http://ejohn.org/blog/sub-pixel-problems-in-css/
http://elasticss.com/determination-of-algorithms-used-for-percentage-based-rounding-divs-on-browsers-and-css-frameworks/
I particularly like this explanation from John Resig/David Baron of why this is even a problem:
I was talking this over with some
Mozilla developers and David Baron
explained the situation quite well:
We’re trying to meet a bunch of
constraints that can’t all be
satisfied at the same time (the proof
is left as an exercise to the reader,
though I may have actually written it
out once in a Bugzilla comment):
4 adjacent objects of width/height 25% (for example) starting at one edge
of a container should end exactly at
the other edge; there should never be
an extra pixel in the container and
they should never be wrapped due to
being a pixel to wide
objects that are logically adjacent should always touch visually; there
should never be a pixel gap or a pixel
of overlap due to rounding error
objects given the same width should occupy the same number of pixels
object boundaries should always (visually) be aliased to a specific
pixel boundary in the display (they
should never be blurred)
The one [Mozilla] sacrifices is
typically (3), except for borders
where we sacrifice (1) by rounding the
widths to pixel boundaries much
earlier.
See this question for a JavaScript fix that forces consistency:
Evenly distributed height of child elements with CSS
Another relevant question:
Are the decimal places in a CSS width respected?
They go in the heaven of pixels ;)
Just joking. Most likely different browsers deal with it in different ways.
The first approach coming in my mind, is to calculate the width of each area. Then round it to the nearest int. The rest of the pixels gets just left empty.
Another approach, could be filling the last area, whatever it is the width (with a small margin of errors).
Very interesting question: it could be nice to have the control over this behaviour with css indeed.
See this post:
Are the decimal places in a CSS width respected?
Depending on what browser you are using changes what happens. Some browsers may round the value. Some force it to round up (math.ceil in some langauges) and some round down or "truncate". For example, Google Chrome truncates the decimals.
You can easily test the effects of this by print screening and then later checking the size in a paint editor (paint, paint.net, adobe photoshop, etc.)
Very interesting question, however :)
Firefox 4:
THe div around these 6 divs has a border. When you slowly resize the whole window you see that the border "jumps". This means all the divs have the same width, but the sum is less/more that 100%.
When you resize just the containing div pixel by pixel, you see that not all the divs change the width simultaneously.
Related
I'm trying to make my own grid which does fit al my needs but I can't find a way to make it the full width at Safari (Mac & iOS). It works nicely in other browsers (Chrome, Firefox, IE10) but in Safari and Safari mobile it leaves a space on the right side.
Are there any solutions for this? I'm a pixel perfectionist so this frustrates me so much.
Image preview:
Demo: http://codepen.io/PatrickVerwoerd/pen/wImcu
This is a sub-pixel rounding error. It's common in any fluid layout, but becomes most obvious when you do the same math over and over (12 equal columns in a row). When you have a fluid layout, there are times when your container (as measured in pixels) doesn't divide evenly by the % you set. Say the viewport is 966px wide, and your columns are 10%. That means each column should be 96.6px wide. Browsers just don't know what to do with that partial pixel. If you resize your container, you'll see that the layout jumps now and then, and lines up exactly right when the container is evenly divisible.
It's an old problem, and browsers have mostly been getting better at handling it. IE used to round up, which caused even worse layout problems. Now, most browsers are smarter about it, but Safari still rounds down.
There's no way to fix the problem entirely. There are no pixel-exact, fluid, floated layouts, but there are several work-arounds. I start with the simplest, and work my way through the list:
When possible, avoid repetitive percentages. Any one element will only ever round down a partial pixel, meaning you never have more than 1px error at a time. If you don't stack the errors, they are easier to hide.
Float the last item in a row to the right. That moves the rounding error in-between columns, where it is generally less noticeable.
If you really can't minimize or hide the errors, in a gallery-style layout for example, try Jon Albin Wilkins' float isolation method. It's a bulky approach, so I don't recommend it everywhere, but it can be real helpful in some cases. Layout systems like Susy and Singularity will also give you that as an option.
With a combination of those techniques, you can keep all your rounding errors to a single pixel. If your designs can't handle a single pixel rounding error, you shouldn't use fluid floats, or you should maybe consider the Dao. :)
The issue is that SCSS in the CodePen is calculating the margin and width to a certain decimal level.
/* Actual Math */
53px / 966px * 100 // = 5.486542443%
/* Codepen Math */
53px / 966px * 100 // = 5.48654%
As you can see the remaining decimals are ignored and therefore your grid is technically not adding up to 100% and therefore a space at the end.
It seems the other browsers are compensating for that by assuming you mean to extend the full 100% whereas Safari is being more accurate (whether that's the correct appraoch will depend on what you're trying to achieve).
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.
I'm having a tough time fully understanding how to use Frameless Grid. I mean, I completely understand the concept. It sounds great.
I guess my beef is just that it doesn't offer anything in the way of positioning your elements. It just sets their width, and that's that. So even if you apply the column widths to your elements, everything just stacks unless you start floating or positioning absolutely.
In this regard, I guess I'm looking for some advice on whether there's some universal positioning styles I can use to keep these elements from stacking.
Or is this just too broad? Should I just be positioning my elements on a case by case basis?
(Also just an FYI I am utilizing SASS, in case that helps at all)
Thanks!
UPD: Frameless Grid has come up with actual code (SASS, LESS and JS), so the answer below is outdated.
Frameless is more of an approach than a grid framework.
It doesn't do anything by itself, other than a single function for grid calculation (even without proper documentation on how to actually use this function).
Let's have a look:
1. Make a regular fixed-width grid.
Pick a column width, a gutter width… you know, the usual stuff. Don’t worry about the amount of columns just yet, but otherwise use whatever criteria it is that you usually use to create fixed-width grids. I recommend using a relatively small column width for added flexibility.
We have to assemble a grid on our own. Use any stuff to acheive that, Frameless doesn't provide any. Column width should be fixed width.
2. Make it repeat infinitely.
Now, give your grid an infinite number of columns, so that no matter how wide you make your viewport, more and more columns come into view. Imagine you’re looking at an infinitely wide honeycomb filled with columns instead of hexagons.
By "infinite number" they seem to mean "any number necessary". Frameless homepage works with fascinating 26 columns (you require display width of 1920px to view that), but frameless.scss only provides variables only for 16 columns.
By "give your grid a number of columns" means "come up with a design that leverages certain amount of columns at maximum".
3. Center it in the viewport.
Align your grid horizontally to the middle of your viewport. For a grid with an even number of columns (pictured), align the center point of your viewport in the middle of the gutter between your two centermost columns. For an odd-numbered grid, align it in the middle of your centermost column.
That's very basic, but it requires us to do another line of CSS code manually.
4. That’s it, really.
Start using the grid. Use media queries to adapt your design as more columns become available. Since you’ll be adapting column by column instead of pixel by pixel, you can choose exactly when your layout should and shouldn’t adapt. This site, for example, only adapts around 320, 480, 600, 900 and 1900 pixels. To see it in action, try resizing your browser window.
No, that's not "it". That's where the work actually starts.
You have to manually code your grid to adapt to various viewports, and Frameless does not provide any tools for that.
So if you're looking for tools that you can use to assemble a grid, i recommend Susy. It's a great and elegant piece of SASS.
Susy is very versatile. It has different grid types (demo). It also has different approaches: you can go content first by declaring single column width and letting Susy adjust the number of columns to match window width. Or you can declare what numbers of columns correspond to what window widths and let Susy adjust column widths accordingly.
Susy lets you achieve what Frameless suggests, but it also provides all the tools necessary. Being different technically, Susy shares the same idea: start with a small grid for mobile phones and make it larges as the screen gets larger. This demo illustrates two such steps: it starts with 7 columns but turns to 12 columns if screen width suggests.
Here i've created a website that uses Susy to stretch in five steps: http://am-teh.ru You can see the code behind this site's layout (and also its concept's evolution) in this StackOverflow post. Susy's developer has commented on it positively.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
what is the difference px,em and ex?
I have a question for all the coding geniuses on StackOverflow.
I am a newbie, and I am about to start building my third website. Being that I had some problems with the layouts of my first two websites, I am asking this question before I start on my third:
What measurement is it best to use for
the css elements? Percents,EM's or Px?
Which form of measurement will ensure that I have a site that will not get distorted on different browser sizes/resolutions? Is there anything else that I have to be careful of when building my site so that it will not get distorted when a user zooms, or looks at the site from a different browser size/ resolution? (as was he case on my other sites)
Thanks for your time, guys. Any help would be greatly appreciated!!
Thank you.
Whichever is easier for you to work with.
Modern browsers (i.e. everything in use today except for IE6 and IE7) have a concept of "CSS pixels" which is different from "actual pixels," so e.g. zooming changes the size of a "CSS pixel." Fonts will scale just fine; if you say the font is 14px, it will start out that way, but if the user zooms it'll get bigger. Thus, if it's easy for you to measure in pixels, for example to size page elements relative to an image of a given pixel size, you should do pixels.
Sometimes you want to size things relative to text, though. If the width of an em-dash is a useful measurement, somewhat representing the "longest possible character," go ahead and use ems.
And finally, if you're trying for a fluid layout, percentages can be great: a gradient that starts fading 50% across the page is often what you want, as opposed to one that starts fading after some fit number of pixels. Even if you're not fluid, and the width of your container is fixed to e.g. 900px, it's still often useful to say "this goes at the 50% mark" or "I have one thing at the 33% mark and one at the 66% mark." That's much easier to work with than figuring out what the corresponding pixel offset is every time, and makes your intent clearer to anyone reading your code.
Short answer: it depends.
Longer answer:
There is a place for all three units, frequently in the same design. There is no "best" unit; they serve different purposes.
Pixel units generally offer the most precise control over the size of the elements in the user interface, but also restrict that size such that it does not change with regard to the other elements of the page design. The size of pixels themselves may change. For example, a Retina display packs more pixels into the same physical space as a non-Retina display, so images which were designed for traditional displays get scaled up. Similarly, traditional desktop web browsers may adjust the size of pixel in response to the user zooming the size of a page. In these cases however, the pixels change sizes throughout the entire document, and retain the same proportions with regard to one another, so you can use px values and expect them to work sanely in most conditions.
EM units vary according to the size of the text. They're most commonly used for setting the size of text, and for line heights; but there have been some interesting things done with "elastic" layouts such as the elastic lawn zen garden (turn off page zoom for this site; switch to text-only zoom and change the size a few times).
Percentages vary according to the size of the containing element, expanding and contracting depending on how much room is available to them.
And, really, it's very common to see web designs that use all of these. For example, suppose you have a site with two columns. The main column must expand and contract with the browser width, but the secondary column needs to stay the same width. The main column might have a width of 100%, but also a margin set in pixels for the secondary column to float in. And the text and line height might be set in ems.
So, the real answer is: they all have their uses. Keep practicing, and pretty soon you'll figure out how it all fits together.
EDIT: In the example above, I should have said "a width of auto" -- meaning take up all available space after margins, padding, and borders are accounted for. Sorry, I tend to think of that as a percentage even though it's actually a keyword.
from accessability point of view need to use EM's. You need you layout to adapt to very different fonts sizes so if allmeasurements are in EM's everything will scale as accessability tools increase font size
When creating liquid layouts, it makes sense to use percentages for the widths of your blocks, so they shrink and grow with browser size changes.
For heights, pts have a specific spatial value, and em are related to your current point size. This is useful because things specified in those units will be roughly the same size on everyone's display (unless they have different zoom factors applied). em are also useful when working with a dimension driven by an amount of text.
Browsers will also scale values specified in pixels, so they are not any more a "trap", but they are rarely the "natural" choice for layouts, unless working with raster images.
As Will and Domenic say: use all three, when appropriate. As you get more experience, you'll get a better feel for when to use which.
If you want to design a fixed layout website then use px or em.
If you want to design a fluid layout website then use percentages.
Percentage is always relative so page content with dimensions in percentage will automatically resize on window resize and on different screen resolutions.
px and em are one and the same thing. Same in their nature. They define the absoluteness of the dimensions. Btw for the difference, 1em=current font size. So if your html or body has css font-size:19px; then 1em=19px.
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.