What is a pixel (px) in CSS? - css

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).

Related

How will pixel widths look on resolutions beyond

If I have all widths on my website set to 1920px
How will it look on higher resolutions (4k for example)? Will it only fill a portion of the site and leave the rest white around it (because this is what happens when I zoom out)?
I guess what I'm really asking is: If I think about the whole website as an image, can I scale it all at once keeping proportion?
EDIT: After some research and trying, i solved it by setting width to 100% and view height (vh) after my needs.
According to the CSS3 values spec, px is an absolute physical length and is supposed to map to approximate real-world dimensions:
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. For reading at arm’s length, 1px thus
corresponds to about 0.26 mm (1/96 inch).
This means that the device itself should be scaling your px measurement appropriately for the display - in terms of 4k, you'll likely see 4 physical pixels for each CSS pixel. This is usually user-configurable in the operating system though, so that isn't a guarantee.
Hardcoding the width of a site is usually a bad idea though - what happens when the browser isn't full screen? How does it appear on mobile devices? You should consider using relative length units like % and em to make your layout more flexible and adapt to these situations.

Web browser support for the point unit

So I have this issue with responsive design. We're supposed to be realigning design for different screen sizes so that we present the best interface for each one.
The thing is that I can't figure out how to do this based on pixels. After all with media queries based on pixel, some of the newer phones look to be larger screens than my 40" tv does. So clearly this is wrong.
I wanted to use points to size things, since a point by definition is 1/72nd of an inch. So I should be able to make something 72pt and expect it to be an inch, this however does not seem hold true.
Does anyone have any idea how to make this work right?
Try using 'em' rather than points or pixels. Set the font-size: 62.5%; on the body tag then for all other elements 1em = 10px, 1.2em = 12px.
Em's are relative unit so with the settings outlined above all elements should scale perfectly proportionally with the screen size. Just be careful with nested elements and generic rules as you can double up occasionally.
Dan Cederholm wrote an excellent book featuring this technique

Which unit of measurement is best for webpage layouts, px, percentages, or ems? [duplicate]

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.

Where do the lost pixels go in a percent CSS layout? [duplicate]

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.

Should I use pt or px?

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.

Resources