Ems vs. percentages vs. pixels - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

83
Ems vs. percentages vs. pixels

Ems, percentages, and pixels are three different units of measurement that you use to style the elements of a webpage. They’re somewhat interchangeable. That is, although I’ve taught you, for example, to express font-size in ems, you can, if you like, express it in pixels or as a percentage.

Pixels are easy to work with, because they’re simple and absolute. With pixels, you don’t have to deal with the sometimes confusing relativism of ems and percentages. But the problem with pixels is that they are absolute. A CSS file full of pixel specifications doesn’t adapt to different-size screens, because it isn’t relative. The need for responsive design forces us to limit our use of pixels and stick mostly to ems and percentages. Here are the rules of thumb that many developers follow, and that I usually follow in this book.

· Ems — Use them for typography, margins, and padding.

· Percentages — Use them for divs, tables, iframes, and sometimes margins and padding.

· Pixels — Use them for images, borders, windows, iframes, and fixed, absolute, and relative positioning (see next chapter).

In your CSS file, style a new div class. Make it less than the full width of the window. Then style a new paragraph class. Make it less than the full width of the div and center it. In your HTML file, code a div of that class and, within it, a paragraph of that class. Save the files. Display the page.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-83-1.html.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-83-2.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/83.html