Home > Articles > Web Services > XML

The Amazing Em Unit and Other CSS Best Practices

This chapter is about writing style sheets with style. By showing you case studies and how they are constructed, we give you a sense of how CSS can encode the visual presentation you want to achieve. More importantly, if you follow the guidelines in this chapter, your documents will behave well on a wide range of Web devices.
This chapter is from the book

This chapter is about writing style sheets with style. By showing you case studies and how they are constructed, we give you a sense of how CSS can encode the visual presentation you want to achieve. More importantly, if you follow the guidelines in this chapter, your documents will behave well on a wide range of Web devices. For example, they will scale gracefully from one screen size to another.

The foremost tool for writing scalable style sheets is the em unit, and it therefore goes on top of the list of guidelines that we compile throughout this chapter: Use ems to make scalable style sheets. Named after the letter "M," the em unit has a long-standing tradition in typography where it has been used to measure horizontal widths. For example, the long dash (—) often found in American texts is known as an "em dash" because historically, it has had the same width as the letter "M." Its narrower cousin (–), often found in European texts, is similarly referred to as "en dash."

The meaning of "em" has changed over the years. Not all fonts have the letter "M" in them (for example, Chinese), but all fonts have a height. The term has therefore come to mean the height of the font – not the width of the letter "M."

In CSS, the em unit is a general unit for measuring lengths (for example, page margins and padding around elements). You can use it both horizontally and vertically, and this shocks traditional typographers who have always used the em exclusively for horizontal measurements. By extending the em unit to also work vertically, it has become a very powerful unit – so powerful that you seldom have to use other units of length.

Let's look at a simple example where we use the em unit to set font sizes:

    H1 { font-size: 2em }

When used to specify font sizes, the em unit refers to the font size of the parent element. So, in the previous example, the font size of the H1 element is set to be twice the font size of the BODY element. To find what the font size of the H1 element will be, we need to know the font size of BODY. Because this isn't specified in the style sheet, the browser must find it from somewhere else – a good place to look is in the user's preferences. So, if the user sets the normal font size to 10 points, the size of the H1 element is 20 points. This makes document headlines stand out relative to the surrounding text. Therefore: Always use ems to set font sizes!

Designers who come from a desktop-publishing background may be inclined to skip the indirection that em introduces and specify directly that the font size should be 20 points. This is possible in CSS (see the description of the font-size property in Chapter 5, "Fonts") but using em is a better solution. Say, for example, that a sight-impaired user sets his normal font size to 20pt (20 points). If the font size of H1 is 2em, as we recommend, H1 elements will scale accordingly and be displayed in 40 points. If, however, the style sheet sets the font size to be 20pt, there will be no scaling of fonts and the size of headlines will have the same size as the surrounding text.

The usefulness of the em unit isn't limited to font sizes. Figure 3.1 shows a page design where all lengths – including the padding and margins around elements – are specified in ems.


Figure 3.1 All lengths on this page are specified using ems.

Let's first consider the padding. In CSS, padding is space around an element that is added to set the element apart from the rest of the content. The color of the padding is always the same as the background color of the element it surrounds. In Figure 3.1, the menu on the right has been given a padding with this rule:

DIV.menu { padding: 1.5em }

By specifying the padding width in ems, the width of the padding is relative to the font size of the DIV element. As a designer, you don't really care what the exact width of the padding is on the user's screen; what you care about is the proportions of the page you are composing. If the font size of an element increases, the padding around the element should also increase. This is shown in Figure 3.2 where the font size of the menu has increased while the proportions remain constant.


Figure 3.2 Because margins and padding are specified in ems, they scale relative to the font size.

Outside the menu's padding is the margin area. The margin area ensures that there is enough space around an element so that the page doesn't appear cramped. This rule sets the margin around the menu:

DIV.menu { margin: 1.5em }

Figure 3.2 identifies the margin area. Again, the use of ems ensures scalable designs.

Another use of ems can be found in this book where the indent of the first line of most paragraphs is set to 1.8 em. The same value is used for the left margin of code examples, such as this:

P { text-indent: 1.8em }
PRE { margin-left: 1.8em }

So, if ems are so great, why does CSS have other units as well? There are cases when it makes sense to use other units. For example, here is a case where percentages may work just as well, if not better: setting the margins of the BODY element. Remember that everything that is displayed in an HTML page is inside BODY, so setting the margins of that element sets the overall shape of the page. You could give the page nice wide margins on both sides with these two rules:

  margin-left: 15%;
  margin-right: 10%

This makes the text 75% of the total width, and the left margin a bit wider than the right one. Try it! Your page immediately looks more professional. Percentage values set on the BODY element are typically calculated with respect to the browser window. So, in the previous example, the text will cover 75% of the browser window.

Both ems and percentages are relative units, which means that they are computed with respect to something. We can distill a general rule from this: Use relative units for lengths. But, how about the absolute units in CSS – inches, centimeters, points, and picas – why are they in there at all if you never recommend to use them?

Cases may arise when you'll need to use absolute units. Say, for example, that you are creating your wedding invitations using XML and CSS. You have carefully crafted tags such as <BESTMAN> and <RSVP/>, and you plan to distribute the invitations through the Web. However, some parts of your families are not yet connected and require printed invitations – on handmade paper, of course, and with proper margins. And 12 point fonts, exactly. This is the time to pull out the obsolete absolute length units: Only use absolute length units when the physical characteristics of the output medium are known. In practice, this happens only when you hand-tailor a style sheet for a specific printer paper size. In all other cases, you are better off using relative length units.

A common presentation on the Web is to move elements to the sides of the page. Typically, this is achieved by using a table for layout purposes. Although you can use CSS to describe table layout (see Appendix A, "HTML 4.0 quick reference"), there is a simpler way to "put stuff on the side." In HTML, images can float; i.e., they move over to the side while allowing text to "wrap around" them. In CSS, all elements – not just images – can float. The menu in Figures 3.1 and 3.2 is an example of a floating element that has been set to float to the right side of the page. To achieve this effect, you must complete two steps. First, the element must be declared to be floating using the float property. Second, the element must be given an appropriate width (in ems, of course). This is done through the width property. Here are the two rules needed:

DIV.menu {
  float: right;
  width: 15em;

By using floating text elements instead of tables, your markup can remain simple while achieving many of the visual effects that are often accomplished with tables in HTML. Thus, we have another guideline: Use floating elements instead of tables. Simpler markup isn't the only reason why floating elements are good replacements for tables. Flexible layout schemes are another. By changing a few lines in the style sheet which generated the page shown in Figure 3.1, we can, for example, move the menu to the left side (see Figure 3.3). Also, many text-only browsers have problems displaying tables because content within the table doesn't come in its logical order.


Figure 3.3 By changing a few lines in the style sheets, you can achieve a different design.

This brings us to the next guideline: Put content in its logical order. Although CSS allows you to move text around on the screen by means of floats and other ways of positioning, do not rely on that. By putting content in its logical order, you ensure that your document makes sense in browsers that don't support CSS. That includes browsers that work in text mode, such as Lynx, older browsers that date from before CSS, browsers whose users have turned off style sheets, or browsers that don't work visually at all, such as voice browsers and Braille browsers. Voice browsers may actually support CSS because CSS can also describe the style of spoken pages, but aural CSS (not described in this book) doesn't allow text to be spoken out of order.

Even a browser that supports CSS may sometimes fail to load the style sheet because of a network error. Therefore, you should always make sure your documents are legible without style sheets. Documents must be legible to humans, but also to Web robots and other software that try to index, summarize, or translate your documents. Also, think of the future: Five years from now, the style sheet may be lost; in 50 years, there may not be a browser that knows CSS; and in 500 years...

A good way to make sure your documents are really legible is to test your documents on several browsers. Alas, not all browsers that claim to support CSS do so according to W3C's specification. How much effort you should put into testing your style sheets depends on the target audience of your documents. If you publish on a closed intranet where everyone uses the same browser, your testing job will be easy. If, on the other hand, your documents are openly available on the Web, testing can be a time-consuming task. One way to avoid doing all the testing yourself is to use one of the W3C Core Styles, which are freely available on the Web (see Chapter 14, "External style sheets").

Realize that your document will end up on systems that have different fonts. CSS specifies five so-called generic fonts that are guaranteed to exist in all browsers: serif, sans-serif, monospace, cursive, and fantasy. When specifying a font family in CSS, you have the option of supplying a list to increase the chance of finding a specified font at the user's system. The last font family in the list should always be a generic font. So always specify a fallback generic font. This book, for example, has been set in Gill Sans. But, not everybody has a copy of that font, so we actually specified the font as

BODY { font-family: Gill Sans, sans-serif }

This code says that the font for the document's body is Gill Sans when available, or any other sans serif font when not. Depending on your browser and your machine's configuration, you may get Helvetica, Arial, or something similar. You can learn more about setting fonts in Chapter 5.

A word of warning at the end: Know when to stop. Be critical when designing your style sheet. Just because you can use 10 different fonts and 30 different colors on the same page doesn't mean you have to – or should. Simple style sheets often convey your message better than over-loaded ones. That single word of red in a page of black gets more attention than any of the words on a page with a dozen different fonts and colors. If you think a piece of your text deserves more attention, give it larger margins, maybe even on all four sides. A little extra space can do wonders.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020