What is the difference between pt and px in CSS? Which one should I use and why?
px ≠ Pixels
All of these answers seem to be incorrect. Contrary to intuition, in CSS the px is not pixels. At least, not in the simple physical sense.
Read this article from the W3C, EM, PX, PT, CM, IN…, about how px is a "magical" unit invented for CSS. The meaning of px varies by hardware and resolution. (That article is fresh, last updated 2014-10.)
My own way of thinking about it: 1 px is the size of a thin line intended by a designer to be barely visible.
To quote that article:
The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.
To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.
Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.
That article gives some guidance about using pt vs px vs em, to answer this Question.
Here you've got a very detailed explanation of their differences
http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/
The jist of it (from source)
Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen.
Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.
Have a look at this excellent article at CSS-Tricks:
px – em – % – pt – keyword
Taken from the article:
pt
The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.
Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.
For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:
px
If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:
Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:
Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:
"Larger" bumped the 16px of the parent into 20px, a 25% increase.
Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.
Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.
A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.
A px is a pixel, which will map on to a screen pixel in most cases.
CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.
A pixel is great if you need to size something to match an image, or if you want a thin border.
Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.
Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)
… and so on.
pt is a derivation (abbreviation) of "point" which historically was used in print type faces where the size was commonly "measured" in "points" where 1 point has an approximate measurement of 1/72 of an inch, and thus a 72 point font would be 1 inch in size.
EDIT: Note to clarify
There are approximately 72 (72.272) points in one inch or 2.54 cm. The point was first established by the Milanese typographer, Francesco Torniella da Novara ( c. 1490 – 1589) in his 1517 alphabet, L'Alfabeto. (you can search for various references to those)
px is an abbreviation for "pixel" which is a simple "dot" on either a screen or a dot matrix printer or other printer or device which renders in a dot fashion - as opposed to old typewriters which had a fixed size, solid striker which left an imprint of the character by pressing on a ribbon, thus leaving an image of a fixed size.
Closely related to point are the terms "uppercase" and "lowercase" which historically had to do with the selection of the fixed typographical characters where the "capital" characters where placed in a box (case) above the non-capitalized characters which were place in a box below, and thus the "lower" case.
There were different boxes (cases) for different typographical fonts and sizes, but still and "upper" and "lower" case for each of those.
Another term is the "pica" which is a measure of one character in the font, thus a pica is 1/6 of an inch or 12 point units of measure (12/72) of measure.
Strickly speaking the measurement is on computers 4.233mm or 0.166in whereas the old point (American) is 1/72.27 of an inch and French is 4.512mm (0.177in.). Thus my statement of "approximate" regarding the measurements.
Further, typewriters as used in offices, had either and "Elite" or a "Pica" size where the size was 10 and 12 characters per inch respectively.
Additionally, the "point", prior to standardization was based on the metal typographers "foot" size, the size of the basic footprint of one character, and varied somewhat in size.
Note that a typographical "foot" was originally from a deceased printers actual foot. A typographic foot contains 72 picas or 864 points.
As to CSS use, I prefer to use EM rather than px or pt, thus gaining the advantage of scaling without loss of relative location and size.
EDIT: Just for completeness you can think of EM (em) as an element of measure of one font height, thus 1em for a 12pt font would be the height of that font and 2em would be twice that height. Note that for a 12px font, 2em is 24 pixels. SO 10px is typically 0.63em of a standard font as "most" browsers base on 16px = 1em as a standard font size.
Yes, "px" means "pixel"
Now that I said it, I can already hear an army of clairvoyants approaching, with "px has nothing to do with pixels" on their banners. They're so proud of knowing better that they look up every comment containing the original truth and explain in detail that it's false, incorrect, misleading, etc.
And yes they have a point - a very specific point in time, actually, called iPhone 4.
Here's what happened.
The peaceful days
Before Retina displays, one pixel was one pixel. Because that's how it should be, according to human logic. You put a single pixel line on the screen, you magnify the hell out of it, and there you go: it's exactly ONE PIXEL wide. On many hardwares, modern ones included, this is still the case, so it's everything but "incorrect" to say 1px = 1 pixel.
But.
Back then, one day, iPhone 3 was followed by iPhone 4, doubling the resolution in both X and Y, and the developers of Safari worried that all webpages will look ricidulous, especially because many web developers relied on the steady 320x480 resolution. So just creating a 640x960 pixel area would have killed most of the sites. And at this point, someone had the billion-dollar idea to introduce a magical beast: a CSS feature called -webkit-min-device-pixel-ratio - on iPhone 3 it was 1, and on iPhone 4 it was set to 2 by default. Meaning "1 CSS pixel now means 2 screen pixels". A very ugly hack to keep websites look somewhat intact - it worked at that time, with the very small cost of some images looking a bit blurry, but in the long run it caused this worldwide misunderstanding of poor old px who actually did nothing wrong.
So then: pt or px?
On screens, use px because on many-many displays it will mean ONE PIXEL. The biggest advantage of using pixels is they look crispy; even if 1px means 2 or 3 physical picture elements, whatever you draw will start at the boundary, not somewhere-in-between. This is very important. Watch any browser animation that includes text, especially size transitions: when you increase a div to double size, but slowly. You'll see how your browser recalculates its pixels and redraws the font when the animation is done. There's a temporary image of the area which is a little blurry - to make the animation itself smoother -, and then, after reaching its final state, a more exact image is calculated. See this CodePen.
1px is always an integer multiplication of hardware pixels; that is, unless your operating system is being smart like resizing your whole desktop to sqrt(2) x PI. Or just 125%, yes, hello Windows on tiny laptops. But anyway - with px, you have the highest chance to align your things with the physical grid.
What about pt? The funny thing about pt is it's actually translated to px, so it's just a worse way to specify pixel sizes. Here's a calculator. Points (since they come from the print world) start to make sense when you print something, but today there are better alternatives, depending on what you need - so tbh, points are almost never needed.
TL;DR
For screens, use px whenever possible.
Related
While delving into CSS units I've encountered a definition of the reference pixel. However, I wasn't able to find a consistent and comprehensive description of its relation to the CSS pixel unit. I've done some research on this matter, yet it's still a little bit unclear to me.
1. Gathered information
1.1 A pixel definition
There are two distinct types/definitions of a pixel:
"Device pixel" — a single physical point on a display.
And:
CSS pixel — a unit most closely matching the reference pixel. [1]
Two parallel concepts under the same name definitely don't clarify the confusion.
I fully understand the purpose of introducing the second one, but I find its nomenclature misleading. The CSS pixel is classified as an absolute unit and:
"Absolute length units are fixed in relation to each other." [1]
The above statement seems pretty obvious for every unit except for the pixel. Following the w3c specification:
"For a CSS device, these dimensions are either anchored (i) by relating the physical units to their physical measurements, or (ii) by relating the pixel unit to the reference pixel.
(...) Note that if the anchor unit is the pixel unit, the physical units might not match their physical measurements. Alternatively if the anchor unit is a physical unit, the pixel unit might not map to a whole number of device pixels." [1]
Considering the aforementioned quotation I assume that absolute units are not all that absolute, since they may be anchored to the reference pixel.
1.2 The reference pixel
The reference pixel itself is actually an angular measurement [2]:
"The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is therefore about 0.0213 degrees." [1]
What is illustrated on the image below:
Despite defining the reference pixel as a visual angle, we can further read:
"For reading at arm's length, 1px thus corresponds to about 0.26 mm (1/96 inch)."
Leaving inconsistencies aside, we are able to establish a value of the angle:
α = 2 * arctan(0.026/142) = 0.02098°
where:
α — a value of the visual angle
Thus a size of the displayed unit equals:
y = 2x * tan(0.01049°)
where:
y — a displayed unit size
x — a reading distance
Given the above formula, in order to calculate a unit size we need to determine what's the actual reading distance. As it may vary among users, its categorisation has been based on a device's DPI.
1.2.1 DPI
For convenience, let's assume that DPI == PPI.
This measurement allows us to guess a display type.
Quick check:
IPhone 6 (4.7", 1334×750): 326 ppi;
Sony Bravia 4K (54.6", 3840×2160): 75 ppi.
So, in general, the bigger PPI the closer to a screen a user sits. The table below [3] presents reading distance recommendations for devices with particular DPI:
———————————————————————————————————————
| DPI | Pixel size | Reading distance |
—————————————————————————————————————————————————————
|PC's CRT | 96 | ~0.2646 mm | ~71 cm |
|display | | | |
—————————————————————————————————————————————————————
|Laptop's LCD | 125 | 0.2032 mm | ~55 cm |
|display | | | |
—————————————————————————————————————————————————————
|Tablet | 160 | ~0.159 mm | ~43 cm |
—————————————————————————————————————————————————————
However, it's unclear to me how those distance values were obtained. Is the relation to DPI described with a function or is it just an empirical observation?
1.2.2 Device Pixel Ratio
The introduction of the Retina display complicated the matter even further. Its PPI tends to be approximately 2 times bigger than non-Retina one's, while a recommended reading distance should remain the same.
Since a CSS pixel size doesn't necessarily correspond with a device pixel size, I assume that the unit size on the Retina display is firstly translated into a reference pixel size (expressed in device pixels) and then multiplied by pixel ratio. Is it correct?
1.2.3 Zooming
While zooming in, the displayed reference pixel size grows [4], ergo a distance from a display grows. It's quite counterintuitive, because it means that we are "stepping away" from the screen, not getting closer to it.
2. Questions
Concluding my doubts and articulating questions:
How a CSS pixel size is calculated when the anchor unit is a physical unit?
How to establish the formula for a relation between DPI and a reading distance?
How a CSS pixel size is calculated for non-standard, high DPI/PPI devices such as printers and Retina Displays?
Also, please correct me if my reasoning is invalid or I am missing something. Thanks for replies.
3. References
W3C Specification
inamidst.com, Sean B. Palmer's site
Mozzilla Hacks
1uirksmode.org
I may be wrong but I don't think it's possible for CSS pixel to have the physical unit as an anchor.
Based on this article:
The px unit is the magic unit of CSS. It is not related to the current
font and also not related to the absolute units. The px unit is
defined to be small but visible, and such that a horizontal 1px wide
line can be displayed with sharp edges (no anti-aliasing). What is
sharp, small and visible depends on the device and the way it is used:
do you hold it close to your eyes, like a mobile phone, at arms
length, like a computer monitor, or somewhere in between, like a book?
The px is thus not defined as a constant length, but as something that
depends on the type of device and its typical use.
UPDATE: I was wrong. It is possible just not implemented in any browser currently. In cases where that is indeed the case, as per spec: "these dimensions are either anchored (i) by relating the physical units to their physical measurements" meaning that 1px will be equal to 1/96th of a physical inch.
As for the relation between DPI and reading distance in the table, it takes that if DPI = 96 then reading distance is ~71cm or 28in and these values are inversely proportional meaning higher DPI will result in a smaller reading distance.
From that it's easy to come up with a formula:
x = 125/96
y = 71/x
where:
x - ratio between second and first DPI value
y - reading distance for second DPI value
For higher resolution devices there is an example given lower in Mozilla Hacks article:
Let’s take iPhone 4 as the most famous example. It comes with a 326
DPI display. According to our table above, as a smartphone, it’s
typical viewing distance is 16.8 inches and it’s baseline pixel
density is 160 DPI. To create one CSS pixel, Apple chose to set the
device pixel ratio to 2, which effectively makes iOS Safari display
web pages in the same way as it would on a 163 DPI phone.
So that means we have two resolutions - physical (PPI) and CSS one (cssppi). It seems that cssppi is used for calculating reference pixel size and then device manufacturers choose how much reference pixels will they map to one CSS pixel (I assume this number is equal to device pixel ratio value but not 100% sure).
Here's table with comparisons for some common devices pixel ratio, PPI, and cssppi: http://mydevice.io/devices/
For more information and reference check following articles:
A List Apart - A Pixel Identity Crisis
Pixels Per Inch Awareness and CSS Px
Physical Size of CSS Units On Smartphones, Tablets & Co
IN THE PAST
1 CSS pixel = 1 pixel on a 96 DPI inch monitor
(common on old windows monitors)
TODAY 1 CSS pixel = (???) pixels on a newer DPI display (smart phones, newer monitors, tv's. etc.)
There are now two different interpretations of the pixel today. The past one and the present one. That's the source of the confusion. But a "CSS pixel" has always been a CSS pixel. It was renamed a "reference pixel" only recently to help associate a CSS pixel's recalculation into "device pixels" on newer HD displays. The old CSS pixel was closely associated with the physical units on screens and printers prior to 2011. At least, the W3C recommendation was asking vendors to follow that spec. It was not till the invention of the iPhone and later HD device screens that the "1 CSS pixel = 1/96th of an inch on a screen" interpretation failed and was abandoned.
The solution was to allow manufacturers with HD screens to "reinterpret", as they like, the "CSS pixel" or "reference pixel" into a new "Device pixel" only they control. So now, how many CSS pixels should fit into a given physical dimension on a screen and its affect on viewers on newer digital devices has changed. The new "device pixel" that tries to follow the 1 CSS pixel = 1/96th of an inch (modified by user viewing distance for smaller screens) no longer applies because screen PPI depth or "pixel density" has increased.
On most newer HD sceens today, the CSS pixel is now recreated across multiple device pixels depending upon the size and PPI of the device. A 72 dpi image on an old Windows monitor would look tiny on a modern iPhone screen, if it did not do that. But you will notice each phone and screen now has its own pixel density (PPI or DPI), screen resolution (pixel width x height), its own physical viewport size (inches), its own default zoom and font resizing systems, its own layout rules (landscape, etc.), and thus their own rules for how they reinterpret the CSS pixel into device pixels (2, 3, 4, etc). You ask what is the formula? I say there is no formula. The industry, in my opinion, does not follow any known standard and has not since abandoning W3C standards after 2010.
Below is some history that may help...
HISTORY OF THE CSS PIXEL
Years ago in the Golden Age of Web Development (pre-2010), defining an "inch" (in) in Cascading Style Sheets would be correctly correlated to an inch on the screen or in print, allowing the 96 pixels per inch to a reader viewing it at arms length always getting the same experience. That was why and how the 96 dots per inch standard was invented. It was designed to force manufacturers to give users the same visual experience with the almighty digital or CSS pixel.
Starting in the 1990's, these CSS standards fell on the shoulders of computer OS manufacturers and their monitors. When it was done right on old Windows and Mac screens prior to 2011, they mapped 96 DPI correctly. You saw Macs and Windows computer screens correctly laying the right pixels per inch onto the screen, so that the CSS "pixel" would fit consistently into it, regardless of manufacturer, vendor, screen, or device. There were visual differences as far as website displays between Macs and Windows due to their slightly different screen dimensions and pixel densities. But that was based on their views of how large or small visuals should be for their viewers. But that did not change the overall CSS standard.
After 2000, an "inch" of website in a browser looked close to an inch on most screens and worked that way for most viewers. Sure, you could increase resolution, or how many pixels could be crammed into a screen. But that did not change the 96 pixels per inch rule, as it worked on the natural assumption a user might choose larger or small text or DPI from the default. This was the same as zoom back then. But after 2000, the CSS pixel and millions of supporting websites fit perfectly on millions of desktop screens, devices, and printed pages.
Prior to 2007, most screens translated every web page and CSS pixel to the "per inch" expectation. So as developers, we initially started trying to fit pixel-based layouts and our favorites font size choices into strict physical layouts using standard 96 dpi and Windows monitors and 72 dpi Mac screens. Of course, after 2001, monitors starting getting larger and resolution settings higher. But everyone knew an inch was still an inch, and a pixel was still a pixel. We could design website layouts to expand and grow based on that 96 DPI standard.
Macs using 72 DPI, we always knew Mac people saw things a little differently, however. As a web developer in 2000, I remember using this system and it worked quite well. But when testing on Macs and Windows, I remember seeing a strange effect...how websites looked slightly larger on Mac screens. Because 72 dpi was the lowest common denominator that is what we used for the default resolution on everything, including sizes of images, web layouts in pixels, etc. That's why there's so much 72 dpi imagery on the web now. But this worked well for over a decade after 2000. CSS pixels worked as expected!
THE IPHONE
After the invention of the iPhone in 2007 the idea of the 96 DPI pixel started to change. Why? The resolution or number of pixels per inch (PPI) increased on tiny screens dramatically. That meant at say 200 PPI, the general resolution of a high density iPhone small screen device, a normal website would look tiny and compressed, the text unreadable and the images less that half their expected size as seen on Windows 96 DPI monitors.
But that is the way the CSS pixel was supposed to work. The way CSS addressed these small-screen, high resolution issues was with the "handheld" media query.
I remember building a website using CSS "handheld" and shifting the pixels in my layout, even revealing higher resolution images for iPhones. This worked initially except for one simple fact.....these new screens and devices REFUSED TO ADOPT THE CSS STANDARDS! Why? They wanted millions of websites to look good out-of-the-box without special CSS adaptions. This is a failure in my book, but se la vi.
So....the W3C by 2011 realized their great standards would never look consistently on these new vendor devices, who wanted quick profits, not standards. So they flipped the definition to start at 96 DPI as a "reference" pixel, then allow vendors to keep creating greater and greater resolution screens but then "reinterpret" the CSS pixel to a "device pixel" they control.
After 2011, the W3C stopped expecting common displays, screens, and devices to correctly define what an absolute dimensional unit in CSS (cm, mm, in, etc) should look like on screens. This was because the vendors making HD screens started increasing resolutions so websites got tinier and tinier until the CSS standards broke. That was when the concept of the "device pixel" was born where devices recreate your CSS pixel by cramming multiple pixels into it.
What does this mean? It means every device automatically regenerates your website design and its reference CSS pixel to a new pixel size. In other words, your website becomes larger and more readable on these tiny screens by default. Your 1 pixel may be remapped to 2 pixels. Average "device pixel" ranges are 2-4 now. Apple iPhone people had no choice in how they chose to translate CSS pixels when their high resolution devices came on the scene. If they didn't adapt to a new device pixel interpretation, we would all be looking at very teeny-tiny 72 dpi GIFs on 400+ dpi retina displays and 4k monitors all over the web. We would have unreadable websites on millions of new modern devices.
You cannot control this. All you can do is focus on avoiding strict pixel-based layouts and PPI/DPI imagery and focus on website layout flexibility. That is why I avoid pixels in 2022 and try and use text-based unit layouts that change based on the user's font-size and using absolute font-size unit layouts and rem/em units rather than pixels. My websites now naturally stretch to fill whatever the screen, phone, monitor, or tv settings use based on the natural size of fonts and text set by the user.
But this is how and why the "device pixel" was born and why pixels now are very difficult to control. The device pixel simply holds double or triple the website pixels given it, in most cases now. It tries to figure out how many web design CSS pixels are crammed into one inch of their physical HD displays.
Kids today building websites just assume its always been that way. They have no clue. That's why most experienced, modern web developers now use relative font sizing and avoid pixels as units for anything. Doing so, your layouts can now stretch based on either the percentages needed to fill the screens and odd view-ports used today, adapt to a user's larger or smaller font sizes, use a user's zoom settings, or just use the default device pixel settings the device uses out of the box. We aren't chained to precise pixel-based layouts any more because of this mess. Pages can stretch in websites to fill what's there. But many kids developing websites still cling to the "css pixel" as if its a God. It's not guys. Its dead.
I think that is how we got here and why new screen technology destroyed what used to be a very simple and elegant website technology. Today its a mess! Why? Because vendors hate standards. They never could come together as a tech industry and define it. There's no money in adopting any of it. So this website pixel translation problem will just get worse as newer devices come online the next 50 years. By then CSS will likely adopt a "hack" that allows us to control how pixels display. In fact in CSS3 you can already sniff for resolutions, set dimensions based on physical view-port sizes, mobile devices, device pixel settings, zoom, media queries, etc.
But those new ideas do not help fix the problem, in my book. They just layer over more complexity and confusion rather than forcing all screen and device manufacturers to use the same, simple CSS pixel, which should be universal across all screens, past and present.
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.
I read somewhere on a site :
In principle, using a px measurement for font-size is not a good idea. A handful of browsers will prevent the font from being resized by the user if you do this.
Is this right??
Is this right??
Well, yes, certainly there are a few (generally older) browsers that won't let you resize the text when it's sized in px, pt, in, mm and so on.
But even in browsers with a working zoom, it's polite to work relative to the user's stated preference for font size, so they don't have to resize the text or zoom the page manually to make it comfortable. (Fixed fonts plus fixed width page can be particularly bad for this in page-zooming browsers as zooming up is likely to make the columns of text too wide to fit the screen.)
In principle, using a px measurement for font-size is not a good idea.
I wouldn't go so far as to say it's always a bad idea.
There are often elements on the page where you want the text to be sized to match an image (say, a header with text below it that should fit more-or-less without wrapping, or text above a background image made to fit it). In that case you should use px to make fonts and images line up nicely.
For the page's main body text, yes, it's nicer to use em/% and let the user decide the size. But for text that plays a part in the page's graphical layout, px fonts are typically the best bet.
The issue is mainly with aspect ratio. Let's say my resolution is 1024x768 for an aspect ratio of 1.33. For 1920x1080, the aspect ratio becomes 1.77, meaning that any image displayed at a specific pixel width and height will be a different size in inches due to the scaling effect of the aspect ratio. The same basic issue exists if you zoom as you are effectively using the aspect ratio in the zoom window.
Most websites get around this by using em which, to be honest, suffers from some of the same downfalls as any other rendering mode. Even "device independent pixels" are based on the DPI of a monitor. So, use em knowing that it just has less faults than px, not because it's perfect.
Read the following article if you want a more in depth study.
http://www.w3.org/WAI/GL/css2em.htm
Yes, at least IE6 & IE7 do that. Take a look at How to Size Text in CSS.
Quoting CSS: The Definitive Guide by Eric Meyer
There is one more value that is
potentially the same as 36pt, and
that's 36px, which would be the same
physical distance if the display
medium is 72 pixels-per-inch (ppi).
However, there are very few monitors
with that setting anymore. Most are
much higher, in the range of 96ppi to
120ppi. Many very old Macintosh web
browsers treat points and pixels as
though they are equivalent, so the
values 14pt and 14px may look the same
on them. This is not, however, the
case for Windows and other platforms,
including Mac OS X, which is one of
the primary reasons why points can be
a very difficult measurement to use in
document design.
Because of these variations between
operating systems, many authors choose
to use pixel values for font sizes.
This approach is especially attractive
when mixing text and images on a web
page, since text can (in theory) be
set to the same height as graphic
elements on the page by declaring
font-size: 11px; or something similar,
as illustrated by Figure 5-15.
Using pixel measurements for font-size
is certainly one way to get
"consistent" results with font-size
(and, indeed, with any length at all),
but there is a major drawback.
Internet Explorer for Windows up
through Version 6.0 does not allow
users to easily resize text that has
been set with pixels. Other browsers,
including Mozilla, Netscape 6+,
IE5+/Mac, Opera, and even IE7, allow
the user to resize text no matter how
it's been set. Thus, using pixels to
size text is no more of a guarantee
that it will stay the same size than
is any other method. The other
approaches discussed in this chapter,
such as keywords and percentages, are
a much more robust (and user-friendly)
way to go, as they can be used to
scale text from the user's default
font size.
That said, the issue here is what unit to use for your body element. In most cases, you should use the em unit for other elements like headings and paragraphs.
Mozilla's documentation from elementFromPoint explains that the coordinates are not in physical pixels, but "CSS pixels". Exactly what are CSS pixels? I was under the impression that a pixel in CSS was the same as the physical pixel.
If this is not the case, how does one convert between physical and CSS pixels?
A pixel is a physical screen pixel as far as any web page can reasonably concern itself.
The wording ‘CSS pixel’ refers to a pixel as defined in CSS 2
the whole number of device pixels that best approximates the reference pixel. It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is therefore about 0.0213 degrees.
What this is saying is that a CSS pixel is a device pixel for the normal, simple screen cases. However, for specialist super-high-res screens where the OS scales up its normal dimensions by two, a CSS pixel may be two device pixels wide.
We now also have a ‘zoom’ feature in most browsers, which will naturally change the size of the CSS pixel (along with all other units) so it doesn't match a device pixel.
As I'm sure you know, CSS provides a number of different units for representing length. Some are based on physical, real-world measurements (inches, millimeters, points) while others are relative to something else (em width, percentage).
But pixels are neither of these. Originally, they were (as you assumed) merely the smallest addressable dot on a user's screen. However, this is problematic for a number of reasons:
The renderer may actually be using sub-pixel positioning to avoid rounding errors.
The output device may not have pixels - a ten-dot font on a 600dpi printer is unlikely to reflect what the designer actually wanted.
Similar to printing, pages designed for common, low-resolution displays (72-96dpi) may be unreadable on high-resolution displays.
Modern browsers offer powerful tools to scale / magnify pages.
And so CSS pixels are a useful abstraction: they have well-defined relations to other measurements (at least, within a given browser...) and thus page designers can rely on the results looking reasonably close to their designs even when the browser must change the relationship to actual, device pixels.
To answer your second question, you don't convert between physical and CSS pixels. That would defeat the whole point by destroying an abstraction that the renderer needs in order to operate properly. Gecko does provide a way to determine the relationship, but only to chrome scripts - normal web pages should remain blissfully unaware...
Further reading: Units Patch Landed
Conversion can be done with window.devicePixelRatio; now supported by all major browsers
See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
In most cases, yes, CSS pixels are the same as physical pixels. According to the CSS 2.1 Specification:
Pixel units are relative to the resolution of the viewing device, i.e., most often a computer display. If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values.
Typically, 1 pixel on the device will be the same as 1 pixel in CSS. On a device with a very high pixel density, you might find that its CSS pixel size is actually 2 physical pixels wide, but I don't know of any devices that do so. Not even the iPhone 4, with its Retina Display, will adjust its CSS pixel size.
As pointed out by Shog9, most browsers' zoom features will adjust the scale of the pixels being displayed, but in most cases, CSS pixels will be the same as the physical device.
I am reading an ASP.NET book and it refers to CSS files and talks about pixels. But I never understood it from a resolution, layout, etc. point of view. For example, what does the following mean in CSS file definition?
#header
{
padding: 0px;
margin: 0px;
}
This is a little beyond where you might be at the moment, but a CSS pixel is not necessarily exactly the same size as a single pixel on your display. According to the spec:
If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values. It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length.
So if you have one of those incredibly expensive extra-high-resolution displays that doesn't count as “typical”, the browser and/or OS may choose to redefine what a “pixel” is.
The useful definition for a ‘px’ as far as CSS authoring is concerned is: a ‘px’ is the quantity of length equal to the pixel in an unscaled HTML <img> or CSS ‘background-image’.
A pixel is generally thought of as the smallest single component of a digital image.
The number of pixels in an image is called resolution.
The screen resolution is the number of distinct pixels in each dimension that can be displayed by your screen.
In the css snippet that you posted you're applying 0 pixels of margin and padding to the element with id="header".
(source: functionx.com)
"A pixel is not a little square" is a good discussion on what a pixel is.
It might not be relevant to your specific question, but if anyone else finds this thread for a computer graphics related problem, this is great reading.
It means a dimension, measured in pixels on-screen. E.g.
width: 200px;
means an element is 200 pixels wide.
A pixel is a "PICture ELement", meaning one coloured dot on the screen, probably much like the period at the end of this sentence.
A pixel is a single dot on the screen. Your example sets the element named header with no padding or margin. To understand this you'll also need to understand the CSS box model for page layout.
A pixel is a unit of measurement, at least, in regards to CSS. There is also pt, em, percentage... there are a few others. Each have their strengths.
W3schools is chock full of references, check the one on CSS.
I recommend downloading Firebug and experiment with changing the pixel width/height.
As stated by others, a pixel is simply a measurable unit that relates directly to the electronic display of data - a single pixel is the smallest an object on screen can be. The greater the screen resolution, the more pixels it can represent.
A note on the example given - a value of 0px is actually unnecessary as a zero value, and is better represented in CSS as just a 0 (it could equally be 0% or 0em, they all mean the same).