📄 Page
1
(This page has no text content)
📄 Page
2
CSS: The Definitive Guide FIFTH EDITION Web Layout and Presentation Eric A. Meyer and Estelle Weyl
📄 Page
3
CSS: The Definitive Guide by Eric A. Meyer and Estelle Weyl Copyright © 2023 Eric A. Meyer and Estelle Weyl. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Amanda Quinn Development Editor: Rita Fernando Production Editor: Elizabeth Faerm Copyeditor: Sharon Wilkey Proofreader: JM Olejarz Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea May 2000: First Edition March 2004: Second Edition November 2006: Third Edition November 2017: Fourth Edition June 2023: Fifth Edition
📄 Page
4
Revision History for the Fifth Edition 2023-05-30: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098117610 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. CSS: The Definitive Guide, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-098-11761-0 [LSI]
📄 Page
5
Preface If you are a web designer or document author interested in sophisticated page styling, improved accessibility, and saving time and effort, this book is for you. All you really need to know before starting the book is HTML 4.0. The better you know HTML, the better prepared you’ll be, but it is not a requirement. You will need to know very little else to follow this book. This fifth edition of the book was finished at the end of 2022 and does its best to reflect the state of CSS at that time. Anything covered in detail either had wide browser support at the time of writing or was known to be coming soon after publication. CSS features that were still being developed or were known to have support dropping soon are not covered here. Conventions Used in This Book The following typographical conventions are used in this book (but make sure to read through “Value Syntax Conventions” to see how some of these are modified): Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP This element signifies a tip or suggestion.
📄 Page
6
NOTE This element signifies a general note. WARNING This element indicates a warning or caution. Value Syntax Conventions Throughout this book, boxes explain a given CSS property’s details, including which values are permitted. This content has been reproduced practically verbatim from the CSS specifications, but some explanation of the syntax is in order. The allowed values for each property are listed with a syntax like the following: Value: < family-name ># Value: < url > ǁ < color > Value: < url >? < color > [ / < color > ]? Value: [ < length > | thick | thin ]{1,4} Value: [ < background >, ]* < background-color > Any italicized words between < and > give a type of value, or a reference to another property’s values. For example, the property font accepts values that originally belong to the property font-family . This is denoted by using the text < font-family >. Similarly, if a value type like a color is permitted, it will be represented using < color >. Any words presented in constant width are keywords that must appear literally, without quotes. The forward slash ( / ) and the comma (,) must also be used literally.
📄 Page
7
Components of a value definition can be combined in numerous ways: Two or more keywords strung together with only space separating them means that all of them must occur in the given order. For example, help me would mean that the property must use those keywords in that order. If a vertical bar separates alternatives ( X | Y ), any one of them must occur, but only one. Given [ X | Y | Z ] any one of X , Y , or Z is permitted. A vertical double bar ( X ǁ Y ) means that X , Y , or both must occur, but they may appear in any order. Thus: X , Y , X Y , and Y X are all valid interpretations. A double ampersand ( X && Y ) means both X and Y must occur, though they may appear in any order. Thus: X Y or Y X are both valid interpretations. Brackets ([…]) are for grouping things together. Thus [ please ‖ help ‖ me ] do this means that the words please , help , and me can appear in any order, though each appear only once. The words do this must always appear, in that order. Here are some examples: please help me do this , help me please do this , me please help do this . Every component or bracketed group may (or may not) be followed by one of these modifiers: An asterisk (*) indicates that the preceding value or bracketed group is repeated zero or more times. Thus, bucket * means that the word bucket can be used any number of times, including zero. There is no upper limit defined on the number of times it can be used. A plus (+) indicates that the preceding value or bracketed group is repeated one or more times. Thus, mop + means that the word mop must be used at least once, and potentially many more times. A hash sign (#), formally called an octothorpe, indicates that the preceding value or bracketed group is repeated one or more times, separated by commas as needed. Thus, floor # can be floor or floor, floor, floor , and so on. This is most often used in conjunction with bracketed groups or value types. A question mark (?) indicates that the preceding value or bracketed group is optional. For example, [ pine tree ]? means that the words pine tree need not be used (although
📄 Page
8
they must appear in that order if they are used). An exclamation point (!) indicates that the preceding value or bracketed group is required, and thus must result in at least one value, even if the syntax would seem to indicate otherwise. For example, [ what ? is ? happening ? ]! must be at least one of the three terms marked optional. A pair of numbers in curly braces ({M,N}) indicates that the preceding value or bracketed group is repeated at least M and at most N times. For example, ha {1,3} means that there can be one, two, or three instances of the word ha . The following are some examples: give ǁ me ǁ liberty At least one of the three words must be used, and they can be used in any order. For example, give liberty , give me , liberty me give , and give me liberty are all valid interpretations. [ I | am ]? the ǁ walrus Either the word I or am may be used, but not both, and use of either is optional. In addition, either the or walrus , or both, must follow in any order. Thus you could construct I the walrus , am walrus the , am the , I walrus , walrus the , and so forth. koo + ka-choo One or more instances of koo must be followed by ka-choo . Therefore koo koo ka- choo , koo koo koo ka-choo , and koo ka-choo are all legal. The number of koo s is potentially infinite, although there are bound to be implementation-specific limits. I really {1,4}? [ love | hate ] [ Microsoft | Firefox | Opera | Safari | Chrome ] The all-purpose web designer’s opinion expresser. This can be interpreted as I love Firefox , I really love Microsoft , and similar expressions. Anywhere from zero to four really s may be used, though they may not be separated by commas. You also get to pick between love and hate , which really seems like some sort of metaphor.
📄 Page
9
It’s a [ mad ]# world This gives the opportunity to put in as many comma-separated mad s as possible, with a minimum of one mad . If there is only one mad , no comma is added. Thus: It’s a mad world and It’s a mad, mad, mad, mad, mad world are both valid results. [ [ Alpha ǁ Baker ǁ Cray ], ]{2,3} and Delphi Two to three of Alpha , Baker , and Delta must be followed by and Delphi . One possible result would be Cray, Alpha, and Delphi . In this case, the comma is placed because of its position within the nested bracket groups. (Some older versions of CSS enforced comma separation this way, instead of via the # modifier.) Using Code Examples Whenever you come across an icon that looks like , it means there is an associated code example. Live examples are available at https://meyerweb.github.io/csstdg5figs. If you are reading this book on a device with an internet connection, you can click the icon to go directly to a live version of the code example referenced. Supplemental material—in the form of the HTML, CSS, and image files that were used to produce nearly all of the figures in this book—is available for download at https://github.com/meyerweb/csstdg5figs. Please be sure to read the repository’s README.md file for any notes regarding the contents of the repository. If you have a technical question or a problem using the code examples, please send an email to bookquestions@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by
📄 Page
10
citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “CSS: The Definitive Guide by Eric A. Meyer and Estelle Weyl (O’Reilly). Copyright 2023 Eric A. Meyer and Estelle Weyl, 978-1-098-11761-0.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North
📄 Page
11
Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/css-the-definitive-guide-5e. Email bookquestions@oreilly.com to comment or ask technical questions about this book. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media. Follow us on Twitter: https://twitter.com/oreillymedia. Watch us on YouTube: https://youtube.com/oreillymedia. Acknowledgments Eric Meyer First, I want to thank all the technical reviewers of this edition, who lent their time and expertise to the arduous task of finding out all the places I’d been wrong, and for less recompense than they deserved. Alphabetically, by family name: Ire Aderinokun, Rachel Andrew, Adam Argyle, Amelia Bellamy-Royds, Chen Hui Jing, Stephanie Eckles, Eva Ferreira, Mandy Michael, Schalk Neethling, Jason Pamental, Janelle Pizarro, Eric Portis, Miriam Suzanne, Lea Verou, and Dan Wilson. Any errors are my fault, not theirs. Thank you as well to all the technical reviewers of past editions, who are too many to name here, and all the people who have helped me understand various bits and bobs of CSS over the years,
📄 Page
12
who are also far too many to name here. If you ever explained some CSS to me, please write your name in the following blank: _______________________, you have my gratitude. Thank you to all the members of the CSS Working Group, past and present, who have shepherded an amazing language to astonishing heights…even as your work means we’ll face a real production dilemma for the next edition of this book, which is already pushing the limits of what printing technology can reasonably manage. Thank you to all the people who keep the Mozilla Developer Network (MDN) up and running as well as up-to-date. Special thanks to all the fine people at Open Web Docs for your work on MDN, and for asking me to serve as a member of your steering committee. To my coauthor, Estelle, thank you for all your contributions, expertise, and pushes to do what was needed. To all the assorted friends, colleagues, coworkers, acquaintances, and passersby who have allowed space for my odd enthusiasms and strange demeanor, thank you for your understanding, patience, and kindness. And as ever, my boundless gratitude to my family—my wife, Kat, and my children, Carolyn, Rebecca z’’l, and Joshua. You are the home that shelters me, the suns in my sky, and the stars by which I steer. Thank you for everything you have taught me. Cleveland Heights, OH December 4, 2022 Estelle Weyl I would like to acknowledge everyone who has worked to make CSS what it is today and all those who have helped improve diversity and inclusion in tech.
📄 Page
13
Many people work tirelessly with browser vendors and developers in writing the CSS specifications. Without the members of the CSS Working Group—past, current, and future—we would have no specifications, no standards, and no cross-browser compatibility. I am in awe of the thought process that goes into every CSS property and value added to, and omitted from, the specification. People like Tab Atkins, Elika Etimad, Dave Baron, Léonie Watson, and Greg Whitworth not only work on the specification, but also take their time to answer questions and explain nuances to the broader CSS public, notably me. I also acknowledge all those who, whether they participate in the CSS Working Group or not, dive deep into CSS features and help translate the spec for the rest of us, including Sarah Drasner, Val Head, Sara Souidan, Chris Coyier, Jen Simmons, and Rachel Andrew. In addition, I thank the people who create tools that make all CSS developers’ lives easier, especially Alexis Deveria for creating and maintaining the Can I Use tool. I also appreciate all those who have contributed their time and effort to improve diversity and inclusion in all sectors of the developer community. Yes, CSS is awesome. But it’s important to work with great people in a great community. When I attended my first tech conference in 2007, the lineup was 93% male and 100% white. The audience had slightly less gender diversity and only slightly more ethnic diversity. I had picked that conference because the lineup was more diverse than most: it actually had a woman on it. Looking around the room, I knew things needed to change, and I realized it was something I needed to do. What I didn’t realize then was how many unsung heroes I would meet over the next 10 years working for diversity and inclusion in all areas of the tech sector and life in general. There are too many people—who work tirelessly, quietly, and often with little or no recognition —to name them all, but I would like to highlight some. I cannot express how much of a positive impact people like Erica Stanley of Women Who Code Atlanta, Carina Zona of Callback Women, and Jenn Mei Wu of Oakland Maker Space have had. Groups like The Last Mile, Black Girls Code, Girls Incorporated, Sisters Code, and so many others inspired me to create a Feeding the Diversity Pipeline list to help ensure that the path to a career in web development is not only
📄 Page
14
for those with privilege. Thank you to all of you. Thank you to everyone. Because of your efforts, more has been done than I ever could have imagined sitting in that conference 10 years ago. San Francisco, CA February 14, 2023
📄 Page
15
Chapter 1. CSS Fundamentals Cascading Style Sheets (CSS), a powerful programming language that transforms the presentation of a document or a collection of documents, has spread to nearly every corner of the web as well as many ostensibly nonweb environments. For example, embedded-device displays often use CSS to style their user interfaces, many RSS clients let you apply CSS to feeds and feed entries, and some instant message clients use CSS to format chat windows. Aspects of CSS can be found in the syntax used by JavaScript (JS) frameworks and even in JS itself. It’s everywhere! A Brief History of (Web) Style CSS was first proposed in 1994, just as the web was beginning to really catch on. At the time, browsers gave all sorts of styling power to the user—the presentation preferences in NCSA Mosaic, for example, permitted the user to define each element’s font family, size, and color. None of this was available to document authors; all they could do was mark a piece of content as a paragraph, as a heading of some level, as preformatted text, or one of a dozen other element types. If a user configured their browser to make all level-one headings tiny and pink and all level-six headings huge and red, well, that was their lookout. It was into this milieu that CSS was introduced. Its goal was to provide a simple, declarative styling language that was flexible for web page authors and, most importantly, provided styling power to authors and users alike. By means of the cascade, these styles could be combined and prioritized so that both site authors and readers had a say—though readers always had the last say. Work quickly advanced, and by late 1996, CSS1 was finished. While the newly established CSS Working Group moved forward with CSS2, browsers struggled to implement CSS1 in an interoperable way. Although each piece of CSS was fairly simple on its own, the combination of those pieces created some surprisingly complex behaviors. Unfortunate missteps also occurred,
📄 Page
16
such as the infamous discrepancy in box model implementations. These problems threatened to derail CSS altogether, but fortunately some clever proposals were implemented, and browsers began to harmonize. Within a few years, thanks to increasing interoperability and high-profile developments such as the CSS-based redesign of Wired magazine and the CSS Zen Garden, CSS began to catch on. Before all that happened, though, the CSS Working Group had finalized the CSS2 specification in early 1998. Once CSS2 was finished, work immediately began on CSS3, as well as a clarified version of CSS2 called CSS2.1. In keeping with the spirit of the times, what was initially coined CSS3 was constructed as a series of (theoretically) standalone modules instead of a single monolithic specification. This approach reflected the then-active XHTML specification, which was split into modules for similar reasons. The rationale for modularizing CSS was that each module could be worked on at its own pace, and particularly critical (or popular) modules could be advanced along the World Wide Web Consortium’s (W3C’s) progress track without being held up by others. Indeed, this has turned out to be the case. By early 2012, three CSS Level 3 modules (along with CSS1 and CSS 2.1) had reached full Recommendation status—CSS Color Level 3, CSS Namespaces, and Selectors Level 3. At that same time, seven modules were at Candidate Recommendation status, and several dozen others were in various stages of Working Draft-ness. Under the old approach, colors, selectors, and namespaces would have had to wait for every other part of the specification to be done or cut before they could be part of a completed specification. Thanks to modularization, they didn’t have to wait. So while we can’t really point to a single tome and say, “This is CSS,” we can talk of features by the module name under which they are introduced. The flexibility permitted by modules more than makes up for the semantic awkwardness they sometimes create. (If you want something approximating a single monolithic specification, the CSS Working Group publishes yearly “Snapshot” documents.) With that established, we’re ready to start understanding CSS. Let’s start by covering the basics of what goes inside a stylesheet.
📄 Page
17
Stylesheet Contents Inside a stylesheet, you’ll find a number of rules that look a little something like this: h1 {color: maroon;} body {background: yellow;} Styles such as these make up the bulk of any stylesheet—simple or complex, short or long. But which parts are which, and what do they represent? Rule Structure To illustrate the concept of rules in more detail, let’s break down the structure. Each rule has two fundamental parts: the selector and the declaration block. The declaration block is composed of one or more declarations, and each declaration is a pairing of a property and a value. Every stylesheet is made up of a series of these rules. Figure 1-1 shows the parts of a rule. Figure 1-1. The structure of a rule The selector, shown on the left side of the rule, defines which piece of the document will be selected for styling. In Figure 1-1, <h1> (heading level 1) elements are selected. If the selector were p , then all <p> (paragraph) elements would be selected. The right side of the rule contains the declaration block, which is made up of one or more declarations. Each declaration is a combination of a CSS property and a value of that property. In Figure 1-1, the declaration block contains two declarations. The first states that this rule will
📄 Page
18
cause parts of the document to have a color of red , and the second states that part of the document will have a background of yellow . So, all of the <h1> elements in the document (defined by the selector) will be styled in red text with a yellow background. Vendor Prefixing Sometimes you’ll see pieces of CSS with hyphens and labels in front of them, like this: -o- border-image . These vendor prefixes were a way for browser vendors to mark properties, values, or other bits of CSS as being experimental or proprietary (or both). As of early 2023, a few vendor prefixes are in the wild, with the most common shown in Table 1-1. Table 1-1. Some common vendor prefixes Prefix Vendor -epub- International Digital Publishing Forum ePub format -moz- Gecko-based browsers (e.g., Mozilla Firefox) -ms- Microsoft Internet Explorer -o- Opera-based browsers -webkit- WebKit-based browsers (e.g., Apple Safari and Google Chrome) As Table 1-1 indicates, the generally accepted format of a vendor prefix is a hyphen, a label, and a hyphen, although a few prefixes erroneously omit the first hyphen. The uses and abuses of vendor prefixes are long, tortuous, and beyond the scope of this book. Suffice to say that they started out as a way for vendors to test out new features, thus helping speed interoperability without worrying about being locked into legacy behaviors that were incompatible with other browsers. This avoided a whole class of problems that nearly strangled
📄 Page
19
CSS in its infancy. Unfortunately, prefixed properties were then publicly deployed by web authors and ended up causing a whole new class of problems. As of early 2023, vendor-prefixed CSS features are nearly nonexistent, with old prefixed properties and values being slowly but steadily removed from browser implementations. You’ll quite likely never write prefixed CSS, but you may encounter it in the wild or inherit it in a legacy codebase. Here’s an example: -webkit-transform-origin: 0 0; -moz-transform-origin: 0 0; -o-transform-origin: 0 0; transform-origin: 0 0; That’s saying the same thing four times: once each for the WebKit, Gecko (Firefox), and Opera browser lines, and then finally the CSS-standard way. Again, this is no longer necessary. We’re including it here only to give you an idea of what it might look like, should you come across this in the future. Whitespace Handling CSS is basically insensitive to whitespace between rules, and largely insensitive to whitespace within rules, although a few exceptions exist. In general, CSS treats whitespace just like HTML does: any sequence of whitespace characters is collapsed to a single space for parsing purposes. Thus, you can format this hypothetical rainbow rule in the following ways, rainbow: infrared red orange yellow green blue indigo violet rainbow: infrared red orange yellow green blue indigo violet ultraviolet
📄 Page
20
rainbow: infrared red orange yellow green blue indigo violet ultraviolet ; as well as any other separation patterns you can think up. The only restriction is that the separating characters be whitespace: an empty space, a tab, or a newline, alone or in combination, as many as you like. Similarly, you can format series of rules with whitespace in any fashion you like. These are just five examples out of an effectively infinite number of possibilities: html{color:black;} body {background: white;} p { color: gray;} h2 { color : silver ; } ol { color : silver ; }