Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Voices That Matter

Designing with Progressive Enhancement: Applying Styles Effectively

In this chapter, learn the best practices for applying CSS with progressive enhancement, including a review of how to divide styles into basic and enhanced style sheets, and techniques to improve the accessibility, usability, and performance of styles.
This chapter is from the book

Cascading Style Sheets (CSS) define the visual styling of a page and allow for a clean separation of presentation from content. A range of advanced typography, visual effects, and sophisticated layouts are all possible with CSS. Applied correctly, these styles can have a huge impact on both the aesthetic appeal and usability of a site.

One of the basic principles of progressive enhancement, and of modern coding practices in general, is to separate presentation from the markup by grouping all style rules into one or more external style sheets. While writing all styles into an external style sheet is an essential best practice for progressive enhancement, on its own this practice does not guarantee a satisfying experience for all users. Every browser will attempt to render any style sheet referenced on the page, regardless of whether or not it properly supports the CSS properties specified. When rendered in capable devices, a style sheet can make a page easier to read or a workflow simpler to follow, but when rendered in browsers that only partially support CSS, it can make the experience confusing or unusable.

When we develop with progressive enhancement, we take the basic principle of separating presentation a step further: we separate styles into "safe" styles that can be served with the foundation markup to all browsers (including those that only partially support CSS), and layer on more complex style enhancements and CSS techniques only after we've tested the browser with our EnhanceJS testing suite and determined that a browser is capable of rendering them properly.

In this chapter, we'll review the best practices we commonly employ when applying CSS with progressive enhancement, including a review of how to divide styles into basic and enhanced style sheets, and highlight techniques to improve the accessibility, usability, and performance of styles.

Applying CSS to the page

There are a number of CSS best practices that apply globally to both basic and enhanced experiences. It's essential to structure styles in external style sheets so they may be logically applied based on browser capabilities, to reference them properly, to target intelligently when appropriate, and to use meaningful naming conventions that characterize styles by their purpose or function rather than their visual characteristics.

Maintaining styles in external style sheets

The first step in maintaining clean separation between markup and styles is to reference all style rules in an external style sheet. This best practice of separating styles from markup has been widely adopted by developers, and is important because:

  • It allows a page to be styled in many ways and easily changed because it doesn't "bake in" a particular appearance
  • It simplifies maintenance by keeping all style rules in one place
  • It minimizes code weight by centralizing shared styles with common classes and IDs rather than repeating them multiple times in the markup

This approach is fundamentally different from the commonly used (but frequently problematic) practice of writing styles inline—for instance, assigning styles to specific elements in the markup with the style attribute (e.g., style="padding: 5px"), or in a style block in the page. Inline styles introduce a number of challenges:

  • They can't be reused across multiple elements on a page or website, meaning inline styles must be duplicated in every place they're needed.
  • They are difficult to maintain and update, because they're embedded within the -content of HTML, rather than being stored in a single external location. Long term, this becomes a maintenance headache, especially if a design changes in any significant way.
  • They won't be controlled by style rules referenced in external CSS. Even if global styles are maintained externally, each instance of an inline style rule in the markup will override any global external styles.
  • Styles served with markup will be rendered by the browser, even if they are not fully supported. Not all browsers handle CSS the same way, or even fully support all CSS2 properties, so in some situations an inline style may render content unusable.

Even in situations where a style is used only once or twice throughout a site, we still recommend listing it in an external style sheet along with all other style rules for the site.

When it's OK to use inline styles: A few exceptions

There are a few very specific cases in advanced UI design where we've found inline styles to be necessary: dynamically positioning elements on the screen, animating elements' style properties, and creating CSS-based charts.

For instance, if you need to center a modal dialog in the screen or iterate the opacity of an element to create a fade transition, it's not practical to create a class for every possible set of position coordinates or for every increment of animated movement. In these cases, it makes sense to use JavaScript to apply a style attribute and modify CSS properties on the fly. We also use inline dimensions to create pure CSS-based charts by styling an element with a percentage width or height for each bar in a chart.

That said, we recommend keeping these inline style rules to an absolute minimum, and using externally referenced CSS for visual presentation whenever possible.

Linking to external style sheets

When we start coding a project, one of the first things we do is create an external style sheet that will house all style rules for the foundation markup, and reference it in the page head:

<link type="text/css" rel="stylesheet" href="basic.css" />

A valid style-sheet link contains the following attributes:

  • type specifies the content type for the server to interpret (for style sheets, it should always be text/css)
  • rel states the relationship of the linked resource to the HTML document (stylesheet)
  • href contains a relative or absolute path to the CSS file

According to the HTML 4 spec, the link element is valid only when listed in the document head, but there's a more important reason to always list it there: any resources listed in the head are loaded before elements in the body. In other words, placing the link element in the head puts styles in place before the page content shows up, so that when it does, it is styled appropriately. Referencing style sheets elsewhere in the page increases the likelihood that the page will load as unstyled HTML, and users will see one or multiple steps of design transformation as styles load—often a suboptimal user experience.

You can also reference multiple style sheets within a single page. When doing so, keep in mind that each style sheet referenced on a page will require a separate HTTP request to the server, and the browser will load every style sheet referenced within the head section of the HTML page before displaying the page content. For these reasons, we recommend combining CSS into the smallest number of files possible.

Targeting particular media types

By default, style sheets referenced with the link element are applied to all media formats, including standard computer screens, mobile devices, and printers.

To flag a style sheet so that it applies only to a particular format, use the media attribute of the link element to apply one or more media types (separating multiple values with commas). For example, this style sheet will apply formatting to print output only:

<link type="text/css" rel="stylesheet" href="basic.css" media="print" />

Media types can also be specified for individual blocks of CSS within a style sheet, to target a few style exceptions to a particular type within a style sheet that applies to a broader range of formats:

@media print {
  h1 { font-size: 16pt; }
  h2 { font-size: 14pt; }
  h3 { font-size: 12pt; }
  #navigation, #advertisement { display: none; }
}

The HTML specification lists a number of media types to choose from, three of which apply to websites and applications:

  • screen renders all associated styles in browsers on standard computer screens
  • print applies formatting for printer output, where layouts are typically set in points and inches, and dimensions are often based on paper sizes
  • handheld applies styles to handheld devices with presumably low bandwidth connections, smaller screens, and limited graphics capabilities

Of these, the handheld media type is, unfortunately, the least reliable. As of this writing, few mobile browsers actually obey this media type and parse styles accordingly. The best way to ensure that appropriate styles are served to mobile devices is to develop with test-driven progressive enhancement to ensure that low-bandwidth, low-capability devices are served a usable experience.

Using meaningful naming conventions

When naming classes and IDs, we recommend using names that describe the content's purpose or role in the content hierarchy, not how it's presented on the screen. Think of classes and IDs as an extension of semantic markup—does the name accurately categorize and identify the content within?

Choosing meaningful naming conventions is a best practice when developing with progressive enhancement for a couple reasons:

  • An element labeled with a class or ID may be styled differently in the basic and enhanced experiences. For example, a column of text in the basic site may be pulled into a modal dialog in the enhanced version. Naming that content according to its purpose provides a logically described hook for applying both safe and enhanced styles, as well as for applying interactivity with JavaScript.
  • Visual design can change, even within a single development cycle. For example, a left navigation bar may be moved to the top or the right side of the page, in which case an ID of left-nav no longer makes sense. It's better instead to use a name that describes the purpose of the navigation, such as primary-nav or secondary-nav.

This point is particularly relevant when CSS may be maintained or extended by multiple developers. As a professional services firm, 90% of the code we write is handed off to clients or provided as open source code to the public. As such, the naming conventions we use should make sense to developers who were not part of the initial build process. Keeping names simple and purposeful, and avoiding cryptic acronyms or jargon that's known only among members of a development team, strengthens the code throughout the life cycle of a project.

Peachpit Promotional Mailings & Special Offers

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

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit 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.

Surveys

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.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. 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.peachpit.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.

Links


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