So I am really at loss which units to adopt when developing responsive layouts. Some say use viewport units
. Other people say use rem
. Other say use media queries and pixel ratio. So what unit is the "right" one, speaking from experience and most bulletproof?
-
On StackOverflow: What's the preferred unit when doing responsive design? – Stephen Ostermiller♦ Feb 11 '16 at 19:59
-
Depends on the designer/framework, some use PX, some use EM, Some use REM. All work... – Simon Hayter♦ Feb 11 '16 at 20:49
-
Use percent for base font size then ems for trickled/bubbled fonts and ratios, percents for margins and things, and px for breakpoints – dhaupin Feb 11 '16 at 23:21
-
This question is off-topic here and belongs on Stackoverflow – Rob Feb 12 '16 at 14:55
To optimize for mobile, you need to have a viewport configured in the meta tag.
This is what I use:
<meta name="viewport" content="width=device-width,initial-scale=1">
That way I'll have pixel units match CSS units when I specify units in pixels in CSS even for mobile.
The only units I use most often for maximum compatibility are:
px - The raw pixel unit. On a desktop, its the size of one tiny dot and takes about 1/(screen width)th of your screen width and 1/(screen height)th of your screen height.
em - I believe it stands for electronic measurement. Its relative to font size. I use it quite often to scale elements. There's more info here: http://www.w3.org/WAI/GL/css2em.htm
Then I do on occasion use percent unit. That means a percentage of the screen.
I'd recommend using the pixel unit only if you have to, such as when you're reserving a block of space for a special advertisement.
I don't bother with the new units because I like to maintain compatibility with all browsers, not just one.
-
I'm not sure what you mean by "raw pixel unit", but it sounds like you're referring to the physical device pixels, in which case this is incorrect. CSS pixels are reference pixels, and can be made up of 1, 1.5, 2, 3, etc. physical pixels. The em unit comes from typography, where it was traditionally equal to the width of the capital letter "M" in whatever typeface was being used. – bernk Oct 29 '18 at 22:39
If you carefully observe most of responsive design css, you will find % as prime unit for width,height,margin etc. For font-size, em is widely accepted. Additionally media queries is also important.