The Book of CSS3 a Developers Guide to the Future of Web Design

308
PX 24 30 A DEVELOPER’S GUIDE TO THE FUTURE OF WEB DESIGN PETER GASSTON THE BOOK OF CSS3 THE BOOK OF CSS3

Transcript of The Book of CSS3 a Developers Guide to the Future of Web Design

CSS3A

THE BOOK OF

DE VELOPERS GUIDE T O T H EF U T U R E O F W E B D E S I G N

PETER GASSTON

24

30

PX

THE BOOK OF CSS3

THE BOOK OF CSS3A Developer's Guide to the Future of Web Design

by Peter Gasston

San Francisco

THE BOOK OF CSS3. Copyright 2011 by Peter Gasston All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. Printed in Canada 15 14 13 12 11 123456789

ISBN-10: 1-59327-286-3 ISBN-13: 978-1-59327-286-9 Publisher: William Pollock Production Editor: Serena Yang Developmental Editor: Keith Fancher Technical Reviewer: Joost de Valk Copyeditor: LeeAnn Pickrell Compositor: Susan Glinert Stevens Proofreader: Nancy Sixsmith Indexer: Nancy Guenther For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 38 Ringold Street, San Francisco, CA 94103 phone: 415.863.9900; fax: 415.863.9950; [email protected]; www.nostarch.com Library of Congress Cataloging-in-Publication Data A catalog record of this book is available from the Library of Congress. No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an As Is basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.

To my wife, Ana, for her patience and support

BRIEF CONTENTS

Foreword by Joost de Valk ............................................................................................xvii Preface ........................................................................................................................xix Introduction ..................................................................................................................xxi Chapter 1: Introducing CSS3............................................................................................1 Chapter 2: Media Queries ...............................................................................................9 Chapter 3: Selectors ......................................................................................................23 Chapter 4: Pseudo-classes and Pseudo-elements................................................................33 Chapter 5: Web Fonts ...................................................................................................49 Chapter 6: Text Effects and Typographic Styles.................................................................65 Chapter 7: Multiple Columns ..........................................................................................81 Chapter 8: Background Images and Other Decorative Properties ........................................93 Chapter 9: Border and Box Effects ................................................................................107 Chapter 10: Color and Opacity....................................................................................119 Chapter 11: Gradients ................................................................................................131 Chapter 12: 2D Transformations ...................................................................................147 Chapter 13: Transitions and Animations ........................................................................163

Chapter 14: 3D Transformations ...................................................................................179 Chapter 15: Flexible Box Layout ...................................................................................195 Chapter 16: Template Layout........................................................................................215 Chapter 17: The Future of CSS .....................................................................................229 Appendix A: CSS3 Support in Current Major Browsers....................................................251 Appendix B: Online Resources......................................................................................257 Index .........................................................................................................................265

viii

Brief Contents

CONTENTS IN DETAILFOREWORD by Joost de Valk PREFACE INTRODUCTION xvii xix xxi

The Scope of This Book .......................................................................................... xxii A Quick Note About Browsers and Platforms ............................................................ xxii The Appendices and Further Resources ....................................................................xxiii

1 INTRODUCING CSS3

1

What CSS3 Is and How It Came to Be ........................................................................ 2 A Brief History of CSS3 ................................................................................ 2 CSS3 Is Modular ......................................................................................... 2 Module Status and the Recommendation Process ............................................. 3 CSS3 Is Not HTML5 .................................................................................... 4 Lets Get Started: Introducing the Syntax ..................................................................... 4 Browser-Specific Prefixes .............................................................................. 7 Future-Proofing Experimental CSS .................................................................. 8 Getting Started ........................................................................................................ 8

2 M E D IA Q U E R I E S

9

The Advantages of Media Queries ........................................................................... 10 Syntax .................................................................................................................. 11 Media Features ...................................................................................................... 12 Width and Height ..................................................................................... 13 Device Width and Height ........................................................................... 15 Using Media Queries in the Real World ....................................................... 16 Orientation ............................................................................................... 17 Aspect Ratio ............................................................................................. 18 Pixel Ratio ................................................................................................ 19 Multiple Media Features ............................................................................. 20 Mozilla-Specific Media Features ................................................................. 21 Summary ............................................................................................................... 21 Media Queries: Browser Support ............................................................................. 21

3 SELECTORS

23

Attribute Selectors .................................................................................................. 24 New Attribute Selectors in CSS3 .............................................................................. 25 Beginning Substring Attribute Value Selector ................................................. 25 Ending Substring Attribute Value Selector ..................................................... 27

Arbitrary Substring Attribute Value Selector .................................................. 28 Multiple Attribute Selectors ......................................................................... 29 The General Sibling Combinator .............................................................................. 30 Summary ............................................................................................................... 31 Selectors: Browser Support ...................................................................................... 31

4 PSEUDO-CLASSES AND PSEUDO-ELEMENTS

33

Structural Pseudo-classes ......................................................................................... 34 The nth-* Pseudo-classes ............................................................................. 35 first-of-type, last-child, and last-of-type .......................................................... 40 only-child and only-of-type .......................................................................... 41 Other Pseudo-classes .............................................................................................. 42 target ....................................................................................................... 42 empty ...................................................................................................... 44 root ......................................................................................................... 44 not .......................................................................................................... 44 UI Element States ....................................................................................... 45 Pseudo-elements ..................................................................................................... 46 The selection pseudo-element ...................................................................... 47 Summary ............................................................................................................... 48 DOM and Attribute Selectors: Browser Support .......................................................... 48

5 WEB FONTS

49

The @font-face Rule ................................................................................................ 50 Defining Different Faces ............................................................................. 51 True vs. Artificial Font Faces ....................................................................... 53 A Bulletproof @font-face Syntax ............................................................................. 54 Using Local Fonts ...................................................................................... 54 Font Formats ............................................................................................. 55 The Final Bulletproof Syntax ..................................................................... 56 The Fontspring Bulletproof Syntax ................................................................ 56 Licensing Fonts for Web Use .................................................................................... 57 A Real-World Web Fonts Example ........................................................................... 57 More Font Properties .............................................................................................. 59 font-size-adjust .......................................................................................... 59 font-stretch ................................................................................................ 60 OpenType Features ................................................................................................ 61 Summary ............................................................................................................... 63 Web Fonts: Browser Support ................................................................................... 64

6 T E X T E F FE CT S A N D T Y P O G R A P H I C S T YL E S

65

Understanding Axes and Coordinates ....................................................................... 66 Applying Dimensional Effects: text-shadow ................................................................ 67 Multiple Shadows ...................................................................................... 70 Letterpress Effect ........................................................................................ 71 Adding Definition to Text: text-outline and text-stroke ................................................... 72 xContents in D eta i l

More Text Properties ............................................................................................... 73 Restricting Overflow .................................................................................. 73 Resizing Elements ...................................................................................... 74 Aligning Text ............................................................................................ 75 Wrapping Text ......................................................................................... 76 Setting Text Rendering Options ................................................................... 77 Applying Punctuation Properties .................................................................. 79 Summary ............................................................................................................... 80 Text Effects: Browser Support ................................................................................... 80

7 MULTIPLE COLUMNS

81

Column Layout Methods .......................................................................................... 82 Prescriptive Columns: column-count .............................................................. 82 Dynamic Columns: column-width ................................................................. 83 A Note on Readability ............................................................................... 84 Different Distribution Methods in Firefox and WebKit ..................................... 86 Combining column-count and column-width .................................................. 87 Column Gaps and Rules .......................................................................................... 88 Containing Elements within Columns ......................................................................... 90 Elements Spanning Multiple Columns ........................................................... 91 Elements Breaking over Multiple Columns ..................................................... 91 Summary ............................................................................................................... 92 Multiple Columns: Browser Support .......................................................................... 92

8 B AC K G R O U N D I M A G E S A N D O T H E R D E C O R A T I V E P R O P E R T IE S

93

Background Images ................................................................................................ 94 Multiple Background Images ....................................................................... 94 Background Size ....................................................................................... 96 Background Clip and Origin ...................................................................... 98 background-repeat .................................................................................. 102 Background Image Clipping ..................................................................... 103 Image Masks ....................................................................................................... 104 Summary ............................................................................................................. 106 Background Images: Browser Support ..................................................................... 106

9 BORDER AND BOX EFFECTS

107

Giving Your Borders Rounded Corners .................................................................... 108 border-radius Shorthand .......................................................................... 109 Differences in Implementation Across Browsers .......................................... 111 Using Images for Borders ...................................................................................... 111 Multicolored Borders ............................................................................................ 114 Adding Drop Shadows ......................................................................................... 115 Summary ............................................................................................................. 117 Border and Box Effects: Browser Support ................................................................ 117Contents in D etai l

xi

10 C O L O R A N D O P A C I TY

119

Setting Transparency with the opacity Property ........................................................ 120 New and Extended Color Values ........................................................................... 122 The Alpha Channel ................................................................................. 122 Hue, Saturation, Lightness ........................................................................ 125 HSLA ..................................................................................................... 127 The Color Variable: currentColor ............................................................... 127 Matching the Operating Systems Appearance ........................................................ 129 Summary ............................................................................................................. 130 Color and Opacity: Browser Support ...................................................................... 130

11 G R A D IE N T S

131

Linear Gradients .................................................................................................. 132 Linear Gradients in Firefox ....................................................................... 132 Linear Gradients in WebKit ...................................................................... 133 Using Linear Gradients ............................................................................ 134 Adding Extra color-stop Values ................................................................. 135 Radial Gradients .................................................................................................. 136 Radial Gradients in Firefox ....................................................................... 137 Radial Gradients in WebKit ...................................................................... 137 Using Radial Gradients ............................................................................ 138 Multiple color-stop Values ......................................................................... 140 The WebKit Advantage ............................................................................ 141 Multiple Gradients ................................................................................................ 141 Repeating Gradients in Firefox ............................................................................... 142 Repeating Linear Gradients ...................................................................... 143 Repeating Radial Gradients ...................................................................... 144 Summary ............................................................................................................. 145 Gradients: Browser Support ................................................................................... 146

12 2 D T R A N S F O R M A T IO N S

147

The transform Property .......................................................................................... 148 rotate .................................................................................................................. 149 Position in Document Flow ........................................................................ 149 transform-origin ....................................................................................... 150 translate .............................................................................................................. 152 skew ................................................................................................................... 153 scale .................................................................................................................. 154 Multiple Transformations ....................................................................................... 156 Transforming Elements with Matrices ...................................................................... 156 Reflections with WebKit ........................................................................................ 159 Summary ............................................................................................................. 161 2D Transformations: Browser Support ..................................................................... 161

xii

C on t e n t s i n D e t a i l

13 T R AN SI TI ON S AN D AN IM A TI O N S

163

Transitions ........................................................................................................... 164 Property ................................................................................................. 165 Duration ................................................................................................. 165 Timing Function ....................................................................................... 166 Delay ..................................................................................................... 168 Shorthand .............................................................................................. 169 The Complete Transition Example .............................................................. 169 Multiple Transitions .................................................................................. 170 Triggers ................................................................................................. 171 More Complex Animations .................................................................................... 172 Key Frames ............................................................................................ 172 Animation Properties ............................................................................... 173 The Complete Animations Example ............................................................ 177 Multiple Animations ................................................................................. 177 Summary ............................................................................................................. 178 Transitions and Animations: Browser Support .......................................................... 178

14 3 D T R A N S F O R M A T IO N S

179

3D Elements in CSS .............................................................................................. 180 Transform Style .................................................................................................... 182 The Transformation Functions ................................................................................. 182 Rotation Around an Axis .......................................................................... 183 Translation Along the Axis ........................................................................ 185 Scaling .................................................................................................. 186 The Transformation Matrix ........................................................................ 187 Perspective ............................................................................................. 188 The perspective and perspective-origin Properties ..................................................... 190 The Transformation Origin ..................................................................................... 191 Showing or Hiding the Backface ............................................................................ 193 Summary ............................................................................................................. 194 3D Transformations: Browser Support ..................................................................... 194

15 FLEXIBLE BOX LAYOUT

195

Triggering the Flexible Box Layout .......................................................................... 196 The box Value in Firefox .......................................................................... 197 Inline Boxes ............................................................................................ 198 Making the Boxes Flexible ..................................................................................... 199 Unequal Ratios ....................................................................................... 201 Zero Values and Firefox Layouts ................................................................ 202 Grouping Flexible Boxes ....................................................................................... 203 Changing Orientation ........................................................................................... 204 Changing the Order of Flexible Boxes .................................................................... 205 Reversing the Order ................................................................................ 205 Further Control over Ordering ................................................................... 206

Contents i n Detail

xiii

Alignment ............................................................................................................ 208 Same-Axis Alignment ............................................................................................ 209 Multiple Rows or Columns ..................................................................................... 211 Cross-Browser Flex Box with JavaScript ................................................................... 211 Stop the Presses: New Syntax ................................................................................ 212 Summary ............................................................................................................. 212 Flexible Box Layout: Browser Support ..................................................................... 213

16 TEMPLATE LAYOUT

215

Setting Up the JavaScript ....................................................................................... 216 Using position and display to Create Rows .............................................................. 216 Multiple Rows ...................................................................................................... 219 Slots and the ::slot() Pseudo-element ........................................................................ 220 Creating Empty Slots ............................................................................................ 223 Setting Height and Width on Rows and Columns ..................................................... 223 Width Keyword Values ............................................................................ 225 Setting Both Row Height and Column Width ............................................... 225 Default Content: The @ Sign .................................................................................. 226 Summary ............................................................................................................. 228 Template Layout: Browser Support .......................................................................... 228

17 THE FUTURE OF CSS

229

Mathematical Operations ...................................................................................... 230 Calculation Functions ............................................................................... 230 Cycle ..................................................................................................... 233 The Grid Positioning Module ................................................................................. 233 Implicit and Explicit Grids ......................................................................... 234 The Grid Unit (gr) .................................................................................... 236 Extended Floats ....................................................................................... 237 Extending the Possibilities of Images ....................................................................... 237 Image Fallback ....................................................................................... 238 Image Slices ........................................................................................... 238 Image Sprites .......................................................................................... 239 Grouping Selectors ............................................................................................... 241 Constants and Variables ....................................................................................... 242 WebKit CSS Extensions ........................................................................................ 245 CSS Variables ........................................................................................ 245 Extending Variables Using Mixins ............................................................ 245 CSS Modules .......................................................................................... 246 Nested Rules .......................................................................................... 247 Haptic Feedback .................................................................................................. 248 Summary ............................................................................................................. 248 Future CSS: Browser Support ................................................................................. 249

xiv

Contents in D eta i l

A C S S 3 S U PP O R T IN C U R RE N T M A J O R B R O W S E R S

251

Media Queries (Chapter 2) ................................................................................... 252 Selectors (Chapter 3) ............................................................................................ 252 Pseudo-classes and Pseudo-elements (Chapter 4) ...................................................... 252 Web Fonts (Chapter 5) ......................................................................................... 252 Text Effects and Typographic Styles (Chapter 6) ....................................................... 253 Multiple Columns (Chapter 7) ................................................................................ 253 Background Images and Other Decorative Properties (Chapter 8) ............................ 253 Border and Box Effects (Chapter 9) ........................................................................ 254 Color and Opacity (Chapter 10) ............................................................................ 254 Gradients (Chapter 11) ......................................................................................... 254 2D Transformations (Chapter 12) ........................................................................... 254 Transitions and Animations (Chapter 13) ................................................................ 255 3D Transformations (Chapter 14) ........................................................................... 255 Flexible Box Layout (Chapter 15) ........................................................................... 255 Template Layout (Chapter 16) ................................................................................ 255 The Future of CSS (Chapter 17) ............................................................................. 255

B O N L I N E R E S O U RC E S

257

CSS Modules ....................................................................................................... 257 Browsers ............................................................................................................. 258 WebKit .................................................................................................. 258 Firefox ................................................................................................... 258 Opera ................................................................................................... 259 Internet Explorer ...................................................................................... 259 Browser Support .................................................................................................. 259 When Can I Use . . . ............................................................................... 259 Quirks Mode .......................................................................................... 259 Find Me By IP ......................................................................................... 260 Feature Detection and Simulation ........................................................................... 260 Perfection Kills ........................................................................................ 260 Modernizr .............................................................................................. 260 CSS3 Pie ............................................................................................... 261 Code-Generation Tools ......................................................................................... 261 CSS3, Please! ......................................................................................... 261 CSS3 Generator ..................................................................................... 261 CSS3 Gradient Generator ........................................................................ 261 Type Folly .............................................................................................. 262 Web Fonts .......................................................................................................... 262 Typekit ................................................................................................... 262 Fontdeck ................................................................................................ 262 Fonts.com Web Fonts .............................................................................. 263 Google Font API ..................................................................................... 263 Web FontFonts ....................................................................................... 263 Font Squirrel ........................................................................................... 263 Fontspring .............................................................................................. 264

C on t e n t s i n D e t a i l

xv

Other Resources ................................................................................................... 264 CSS3.info .............................................................................................. 264 CSS3 Watch .......................................................................................... 264 CSS3 Cheat Sheet ................................................................................... 264

INDEX

265

xvi

Contents in D eta i l

FOREWORD

CSS3 used to be a topic for people who were in it for the long haul. Back in 2006, I started CSS3.info, and Peter joined me in writing posts about the development of the standard and real-life examples of whatit looked like in browsers. Although I started the site, Peter was always the most prolific writer, and its only fitting that while I wrote this foreword, he wrote the book. CSS3 has finally gone mainstream. With the new age of browsers (such as Firefox 4, Google Chrome, and Internet Explorer 9), we as a web design community are finally getting the power and flexibility weve been waiting for. We can now manage media queries for different browsers, have smarter background images, and handle fonts in a way that doesnt drive us nuts. If you plan on using CSS3, this book is the most hands-on guide youll find. It shows you what works and what doesnt, and no caveat is forgotten. Peter even provides a clear explanation for how transitions and transformations work. This is no small feat; as youll see for yourself when reading those chapters, the matrix functions are not for every user. Luckily you wont have to use those when youre taking advantage of the otherfar more accessiblefunctions in CSS3.

More is to come: CSS3 is an ever-expanding standard that promises to help web designers do great things. I, for one, am very curious about where it will lead us. For now, though, this book is all you need to start uncovering the treasures within CSS3. Joost de Valk CEO and Founder, Yoast.com

xviii

Fo rew or d

PREFACE

This book is the culmination of five years writing about CSS3, both on the Web and in print. The browser and CSS landscape has changed a lot in that short time and continues to change today, bringing new features andimplementations at a rate thats difficult to keep up with. The CSS3 specification is written in (often dense) technical language thats intended for implementers rather than end users, and my intent in writing this book was to bridge the gap between specification and web developer. I wrote about the CSS properties in the earlier chapters of this book with certainty, because theyre well implemented and used on a daily basis. As I progressed through the book, I was able to learn more from experimentation and the work of pioneers and early adopters. By the final few chapters I had to rely on interpretation of the CSS3 specification to explain how future properties will behave. I would hope that there are few mistakes, but I accept that any that exist are based on my own misunderstanding. In addition to the CSS3 specification itself, an invaluable resource was the Mozilla Developer Network (https://developer.mozilla.org/), a peerless collection of articles about anything web relatednot least CSSwhich is all the more amazing for being written by volunteers. The text used in many of

the code examples is taken from books in the public domain which are available at http://www.gutenberg.org/. All images in the book that are not my own creations are credited in the relevant chapters. This book would not have been possible without the guidance of the team at No Starch Press, especially Serena Yang and my editor, Keith Fancher, who made me write more clearly and helped me transition from blogger to author. Id also like to thank Joost de Valk, who not only acted as my technical editor but also gave me my first opportunity to write about CSS3 when he created the website http://www.css3.info/ five years ago. Id also like to thank my colleagues at Preloaded and Poke for their support and encouragement, everyone at the many London web community meet-ups, my mum for teaching me the value of hard work, and my dad for buying me my first computer some almost thirty years agoI promised Id pay him back one day, and hopefully this book will go some way toward that debt.

xx

Preface

INTRODUCTION

Let me tell you a little about who I think you are: Youre a web professional whos been hand-coding HTML and CSS for a few years; youre pretty comfortable with creating complex layouts, and you know not only your div from your span but also your bold from your strong; youve read2430

a little about CSS3 and may even have started experimenting with some of its more decorative features like rounded corners, but you want to gain a deeper understanding of the fundamentals. The Book of CSS3 helps you leverage the excellent knowledge you have of CSS2.1 in order to make learning CSS3 easier. I wont explain the fundamentals of CSS (except for the occasional reminder) as I assume you know them already. I wont talk you through step-by-step demonstrations of using CSS to make a listed navigation or an image gallery because I assume you can apply the examples in this book to anything you want to build on your own.

PX

What I aim to do with this book is introduce you to what you can do with CSS3 now and what youll be able to do with it in the future. I want to take the dense technical language of the CSS3 specification and translate it into language thats plain and practical. In short, I want to give you some new tools for your toolkit and let you make cool stuff with them.

The Scope of This BookCSS can be used across many types of media; almost any device thats capable of displaying HTML or XML can also display CSS rules, albeit in a limited form sometimes. CSS3 has two modules devoted exclusively to paged media, such as PDF or printed materials, and also supports braille, handheld mobile devices (i.e., cellphones rather than smartphones), teletypes, and televisions. The range and breadth of possibilities is so vast that I cant cover them all. What this book focuses on is CSS for the computer screen. All of the demonstrations were written for (and tested in) the most common desktop browsers, and theyre optimized for users of desktop and laptop computers. Although many of the new features in this book will still work if youre developing for other devicesespecially smartphones and tabletsI make no guarantees or assurances that everything will display exactly as shown in the examples contained herein.

A Quick Note About Browsers and PlatformsI wrote the majority of this bookand, therefore, the majority of the demonstrations and exampleson a computer running Ubuntu 10.04 with Firefox, Chrome, and Opera installed. Other portions were written on a MacBook Pro with Safari installed. Tests for Internet Explorer were performed using Windows 7. (The exact versions of all of the browsers used can be found in the introduction to Appendix A.) Throughout this book, I mostly make reference to Firefox and WebKit. The perspicacious among you will notice that Firefox is a type of browser, whereas WebKit is a type of layout engine, and wonder why I dont refer to the Gecko layout engine used by Firefox or to any WebKit-based browser by name. The reason is quite simple: Firefox is clearly the preeminent Gecko-based browser, whereas Chrome and Safari dispute the eminence of WebKit between them. As a simple space-saving exercise, I will say WebKit rather than Chrome and Safari. The exception to this rule is when a specific feature or syntax only appears in one type of WebKit browsersuch as hardware-accelerated 3D transformations in Safariin which case, I refer to the name of the browser in question.

xxii

I n t ro d u c t i o n

The Appendices and Further ResourcesAt the end of this book are two appendices containing further information beyond whats discussed in the various chapters. The first provides a quick reference guide to the implementation of the features included in this book across the different versions of browsers, and the second is a list of online resources, useful tools, and interesting demonstrations. A website accompanies this book at http://www.thebookofcss3.com/; here Ill keep updated versions of both appendices and all of the examples and demonstrations used in this book. God forbid I should make any mistakes, but on the super-rare possibility that I do, Ill also keep a full list of errata. In addition to the accompanying website, I write more about CSS3 (and other emerging web technologies) at my blog, Broken Links (http://www .broken-links.com/ ). Feel free to comment or get in touch with me through either of these websites.

I n t ro d u c t i o n

xxiii

INTRODUCING CSS3

In this first chapter, Ill introduce a new CSS3 property in order to demonstrate the code conventions used in this book, but before getting to that, Ill explain a little about the history of CSS3. Obviously, you dont need to know its history in order to use CSS3, but I think having some context about the current state of CSS3 is important.2430

CSS3 is a specification in flux. Some parts of the spec are considered stable and have been well implemented in modern browsers; other parts should be considered experimental and have been partially implemented to varying degrees; yet others are still theoretical proposals and have not been implemented at all. Some browsers have created their own CSS properties that dont belong in any CSS3 specification and perhaps never will. All of this means that knowing how the standardization process works and the levels of implementation for each new property is vital to understanding how you can use CSS3 in your code both now and in the future.

PX

What CSS3 Is and How It Came to BeFirst, I want to discuss what CSS3 isand isntand the form it takes. The W3Cs approach to CSS3 is quite different from its approach to CSS2, so this overview should help you understand how and when you can use CSS3 and why it has such varied implementation across different browsers.

A Brief History of CSS3The version of CSS in current use is CSS2.1, a revision of the CSS2 specification that was originally published in 1997. Despite ongoing development and review since that time, many people are surprised to learn that CSS2 hasnt actually become an official recommendation of the W3C yet. (Ill talk more about the recommendation process shortly.) More surprising still is the fact that Internet Explorer 8 (IE8)released in 2009lays claim to being the first browser to support the entire CSS2.1 specification fully. In the last few years, the talk has been about the new revisionCSS3. I say new, but in fact work on CSS3 began back in 1998, the year after CSS2 was published. Browser implementation of CSS2 continued to be so frustratingly inconsistent, however, that the W3C decided to halt work on any new revision and work on CSS2.1 instead, standardizing the way CSS had been implemented in the real world. In 2005, all of the CSS3 modules were moved back to draft status, and the editing and review process began all over again. For many years, Internet Explorer dominated the ever-expanding market of Internet users and showed no sign of wanting to implement CSS3. But in the last few years, a whole new range of browsers has appeared to compete for users, and this plethora of choice has led to a features arms race. One beneficiary of that arms race has been CSS3. Each of the browsers wants to offer developers and users the latest in web technologies, and with the CSS3 spec already mostly written, implementing and even adding new features has been a no-brainer. So here we are today, with the CSS3 specification under active development, a broad range of browsers working on implementing it, and a community of interested developers building with it, studying it, and writing about it. A healthy situation, and one we couldnt have foreseen just a few years ago.

CSS3 Is ModularBeing the default styling language for every markup-based document in the world is an enormous undertaking, and the W3C was aware that it would take many years to come to fruition. W3C members, conscious that they didnt want to hold up some of the more obvious, in-demand features while they were considering and debating some of the more esoteric ones, made the decision to split CSS3 into various modules. Each of the modules could then be worked on by different authors at different paces, and the implementation and recommendation processwhich Ill discuss shortlycould be staggered. This is why, instead of a single, monolithic CSS3 specification document, you have CSS3 Basic User Interface Module, Selectors Level 3, Media Queries,2Chapter 1

and so on. Some of these modules are revisions of CSS2.1, and some are newly created, but all fall under the banner of CSS3. One of the few things I find irritating (Im an easy-going guy) is that on many blogs youll hear people complaining, I want to use CSS3, but it wont be ready for years. This is nonsense; some modules of CSS3 already have very stable implementation in all modern browsers, and many more are just months away from prime time. If you want to wait until all of the modules are 100 percent implemented across every browser in existence, youll be waiting a long time. But CSS3 is here, and some of it is ready to use right nowyou just have to be mindful about how you use it.

Module Status and the Recommendation ProcessAs I move through this book and discuss each of the different modules, Ill also refer to that modules status. Status is set by the W3C, and it indicates the modules progress through the recommendation process; note, however, that status is not necessarily an indication of a modules degree of implementation in any browser. When a proposed document is first accepted as part of CSS3, its status is designated Working Draft. This status means that the document has been published and is now ready for review by the communityin this case, the community being browser makers, working groups, and other interested parties. A document may stay as a Working Draft for a long period, undergoing many revisions. Not all documents make it past this status level, and a document may return to this status on many occasions. Before a document can progress from a Working Draft, its status changes to Last Call. This means the review period is about to close and usually indicates the document is ready to progress to the next level. That next level is Candidate Recommendation, which means the W3C is satisfied that the document makes sense, that the latest reviews have found no significant problems, and that all technical requirements have been satisfied. At this point, browser makers may begin to implement the properties in the document to gather real-world feedback. When two or more browsers have implemented the properties in the same way and if no serious technical issues have come to light, the document may progress to being a Proposed Recommendation. This status means that the proposal is now mature and implemented and ready to be endorsed by the W3C Advisory Committee. When this endorsement has been granted, the proposal becomes a Recommendation. To reiterate what I briefly touched on before, the recommendation process and the implementation process do not always work in the same way. For example, later on in this book, Ill introduce a set of modules proposed by the WebKit team a few years ago, which includes 2D Transformations (Chapter 12). Despite the proposal still having Working Draft status, the properties are already well implemented in Firefox, Opera, and WebKit. As I mentioned earlier in this chapter, not even CSS2.1which weve all been using for many years nowhas reached full Recommendation status.I n t r od u ci n g C S S 3

3

Although CSS2.1 is as good as finished, a few matters of syntax and phrasing still need to be resolved. Obviously, that hasnt stopped the browsers from implementing it fully and moving on to CSS3. As a result, Ive written this book in a loose order of implementation, rather than recommendation status. Earlier chapters discuss features that have full implementation across all browsers (or should by the time this book is released), later chapters cover features that are implemented in some browsers onlyoften with browser-specific prefixesand chapters toward the end of the book deal with potential, speculative, or partial implementations of properties.

CSS3 Is Not HTML5One of the current buzzwords around the Internet is HTML5. HTML5 is, of course, a genuine (and exciting) new technology that has somehow broken out of the technical press and through to the mainstream media. Just about everywhere you turn people are discussing it. On that journey, however, its correct meaning seems to have been lost. Before I discuss what that real meaning is, I should point out that the media are not solely responsible for obfuscating the true meaning of HTML5. Many developers are falling over themselves to make flashy HTML5 demos; but if you look more closely at these demos (or view their source code), more often than not youll find they involve few-to-no actual new HTML5 features and an awful lot of CSS3 (yes, Apple, Im looking at you: see http://www.apple.com/ html5/). Although HTML5 will bring a lot of cool new features to the Web, CSS3 is bringing the really fancy visual stuff: rotating, scaling, and animating in two and three dimensions; dynamic and decorative text effects; drop shadows; rounded corners; and gradient fill effects. All this is possible with CSS3 (and Ill show you how to do it all in this book). What the media refers to as HTML5 is really that new revision of the markup language combined with CSS3, SVG, and JavaScriptwhat many people (myself included) prefer to call part of the Web Stack (or, Open Web Stack).

Lets Get Started: Introducing the SyntaxWith the introductions and explanations out of the way, lets get to the meat of CSS3. Throughout this book, I use a certain syntactical convention to demonstrate each of the new rules and properties. Rather than simply describe that convention, I thought youd find it more interesting if I explain it at the same time as I introduce the first new CSS3 property. The property is box-sizing, which allows you to set how an elements dimensions are calculated. As you know, an elements total widthwithout including its marginis usually calculated from its stated (or inherited) width value, plus its left and right padding, plus its border-width. Lets take as an example the following code, which should be very familiar to you.

4

Chapter 1

div { border: 10px solid black; padding: 10px; width: 150px; }

In this example, the div has a total width of 190px150px width plus 20px padding plus 20px border. This code is fine and uncontentious when youre using absolute values for width, but it becomes problematic when you start mixing in percentages:div { border: 10px solid black; padding: 10px; width: 15%; }

Now the width has become a lot harder to calculate because you first need to know the width value of the parent element before you can know how much 15 percent of that is and add the pixel values. Calculations can become very complicated very quickly, making percentage-based layouts tricky to manage properly. At this point, the box-sizing property comes in handy. With this, you can set from which part of the box modelthe content itself or the borderthe width of the element is calculated. So now that Ive covered the reason for the new propertys existence, Ill begin the demonstration with a look at its syntax, using the convention that will be standard in this book:E { box-sizing: keyword; }

In this code example, the selector is represented with E. Of course, in HTML, this selector doesnt exist; Im merely using it as an indicator that any selector can be used here. In the case of the examples used at the beginning of this section, the E represents the div element. Next, you have the property itself: box-sizing. This property is implemented in all major browsers but with browser-specific prefixes in some: In Firefox, the property uses the -moz- prefixthat is, the property is -moz-box-sizing; and in WebKit, it has the -webkit- prefix, so it would be -webkit-box-sizing. Rather than obfuscate the code with all of the different prefixes, I use only the correct property name according to the CSS3 specification and note in the text when a prefix is required, as Ive just done here. (Ill explain more about these browser prefixes in the following section.) The value of the declaration is the word keyword, but again the value is only an indicator; it represents a range of possible values. For box-sizing the permitted values are border-box and content-box.

I n t r od u ci n g C S S 3

5

With all of that in mind, if you used actual values, one possible real-world application of this new property might look like this:div { box-sizing: content-box; }

So what does this property do? As mentioned, box-sizing sets the point of the element from which the width is calculated. The default is content-box, which means the stated width of the element applies to the content, and the padding and border values are added on as usual. A value of border-box means the stated width value is the total width of the content, the padding, and the borderin other words, the entire box (without the margin). To illustrate this, lets return to the previous example code and add the property:div { border: 10px solid black; box-sizing: border-box; padding: 10px; width: 150px; }

Now the width of 150px includes the padding and border. As each of those is 10px on both sides, the content of the div element has a calculated width of 110px150px minus the 20px padding and 20px border. Before illustrating the difference between the two values visually, I should also mention that Firefox (with its -moz-box-sizing property) has an extra permitted value that other browsers dont: padding-box. Using this value, the width of the element is calculated from its padding and its content and doesnt include the elements border. Heres an example:div { border: 10px solid black; -moz-box-sizing: padding-box; padding: 10px; width: 150px; }

In this code, the 150px width includes the padding, so the width of the content itself would be 130px. You can see the difference among the values when rendered in Firefox in Figure 1-1. Moving through the examples from left to right: The first div has the default content-box value for box-sizing, so the stated width150pxis the width of the content, and the border and padding are added to the content. In the second example, the value is border-box, meaning the 150px width includes the border and padding, making the content 110px wide. Finally, the div on the right uses Firefoxs own -moz-box-sizing property with the value of padding-box, so the 150px includes the content and padding but not the border, putting the contents width at 130px.

6

Chapter 1

Figure 1-1: The effects of different values on the box-sizing property

Please note that although I only discuss the width property in all of these examples, the exact same rules apply to an elements height property. (You may also note that this works in exactly the same way as a browser that is put into quirks mode.)NOTE

If youre a younger developer you may not remember quirks mode. Its a system that emulates the incorrect way that Internet Explorer 5.5 used to lay out web pages; you can read more about it on Wikipedia (http://en.wikipedia.org/wiki/Quirks_mode). I use the box-sizing property in a few examples throughout this book, so if the effects (and benefits) arent immediately apparent right now, they should become clearer as you work through the rest of the chapters.

Browser-Specific PrefixesIn the previous section, I briefly discussed using browser-specific prefixes on the box-sizing property. As CSS3 is still in a state of change and revision, youll see these mentioned a lot throughout the rest of this book, so Ill take some time to talk about these in more detail. When a module is still under active review, as much of CSS3 is, a lot is subject to change; the syntax of a property may be revised, or properties may be dropped entirely. On occasion, even the wording of the draft itself is perhaps a little nebulous and open to interpretation. At the same time, browsers need to implement these features so we can see how they work in practice. But consider the difficulties that would occur if two separate browsers implemented the same property but interpreted it slightly differently: Your code would appear differentlyperhaps radically soin each of the browsers. To prevent this from happening, each of the different browser engines prefixes a short code to the beginning of experimental properties. Lets imagine a property called monkeys (Ive always wanted a monkeys property), which is brand new in the specification, and that all of the browsers have decided to implement it to see how it works. In this case, you would use the following code:E { -moz-monkeys: value; /* Firefox */ -ms-monkeys: value; /* Internet Explorer */I n t r od u ci n g C S S 3

7

-o-monkeys: value; /* Opera */ -webkit-monkeys: value; /* WebKit */ }

The amount of repetition may seem somewhat unnecessary, but the repetition is for our own good; the last thing you want is for all the browsers to implement the monkeys property differently, leading to total chaos. (Youll see a great example of the benefits of prefixes when I discuss gradients in Chapter 11.)

Future-Proofing Experimental CSSQuite often people will suggest that when using prefixed, experimental CSS properties, you also add the unprefixed property at the end:E { -moz-monkeys: value; /* Firefox */ -ms-monkeys: value; /* Internet Explorer */ -o-monkeys: value; /* Opera */ -webkit-monkeys: value; /* WebKit */ monkeys: value; }

The theory is that this future-proofs the code; when the property is fully implemented in the browsers, you dont need to go back and add the property to your stylesheets. I used to agree with this technique, but now Im not so sure. I think future-proofing is okay if more than one browser has already fully implemented the property in a compatible way, as that usually means the specification is stable. However, if the spec is still under review, then the syntax is subject to change. Adding the unprefixed property could cause problems when browsers actually implement the updated syntaxor, indeed, it may not work at all. Some properties in this booksuch as background-size in Chapter 8 are semi-implemented, which is to say they are prefixed in some browsers, but unprefixed in others. In this case, you will obviously have to use a mixture of the two states if you want to use those properties across browsers. Otherslike the aforementioned gradient properties in Chapter 11are immature, still open to review, and far from final, so you should probably not use the future-proofing method with them just yet.

Getting StartedThat should be everything you need to get started with this bookexcept, of course, an inquisitive nature. I have a lot of ground to cover in CSS3, so Ill move fairly quickly, but each chapter should give you the knowledge you need to build your own tests, demonstrations, and sites that take advantage of the flexibility and rich features that CSS3 provides. Well begin with a look at one of the simplestand yet potentially the most disruptive (and I mean that in a good way)new features: Media Queries.8Chapter 1

MEDIA QUERIES

Back when the World Wide Web was something you only accessed via a browser on your desktop or laptop, writing CSS was fairly straightforward. Although you had to consider cross-browser and cross-platform issues, at least you knew with reasonable certainty that everyone2430

was using fundamentally similar devices to view your website. Over the last few years, however, weve seen an explosion of new devices for accessing the Webfrom game consoles to mobile devices such as the iPhone or iPad. Presenting your content to everybody in the same way no longer makes sense when they could be viewing your website on a widescreen desktop monitor or a narrow handheld screen. CSS has had a way to serve different styles to different media types for quite some time, using the media attribute of the link element:

But using this is like wielding a pretty blunt instrument when the screen in question can be between 3.5 inches and 32 inches in size. The

PX

CSS3 solution to this problem is the Media Queries Module (http://www.w3.org/ TR/css3-mediaqueries/). Media Queries extend the media types by providing a query syntax that lets you serve styles far more specifically to your users device, allowing a tailored experience. The description may sound quite dry, but this feature is actually one of the most revolutionary in the entire CSS3 specification. Media Queries give you the freedom to make websites that are truly device-independent and give your users the best possible experience no matter how they choose to visit your site. The Media Queries Module has Candidate Recommendation status so is considered ready for implementation. The module is already well implemented in Firefox, WebKit, and Opera, and will be in Internet Explorer from version 9.

The Advantages of Media QueriesAs a quick demonstration of the power and flexibility of Media Queries, I want to show an example of how websites can be optimized for mobile browsers without requiring a great deal of extra development. People visiting your site on a mobile device may well struggle to use it: The text may appear too small, and zooming in means a lot of scrolling to find navigational elements; those navigational elements may involve dropdown functionality that is triggered by hovering over them, an action that often doesnt exist on mobile devices; large images may take a long time to download over a weak data connection and use a substantial portion of your monthly bandwidth allowance. Some sites plan for this by providing mobilefriendly versions, but these generally involve a lot of development work. A subdomain has to be set up with stylesheets and HTML templates that differ from the parent site, images have to be resized to better fit small screens, and a script has to be created to detect whether a mobile browser is being used and to redirect to the mobile site accordingly. This approach can cause problems: Your script has to be kept up to date with all mobile browser versions, and maintenance often involves duplication to keep both mobile and desktop versions in sync. Media Queries address many of these issues. For a start, they detect devices based on their attributes, so no browser-sniffing scripts are required. They allow you to target stylesheets directly for a devices capabilities, so if a device with a small screen is detected, CSS rules will be tailored to that screen size, removing extraneous elements from the screen, serving smaller images, and making text clearer. For example, take a look at the website of the dConstruct conference from 2010 (http://2010.dconstruct.org/), as shown in Figure 2-1. When viewed in a desktop browser, the site features large images of the speakers, and text is displayed in columns laid out horizontally. Through the power of Media Queries, when you see the same site viewed in a narrower browseras smartphones such as the iPhone would usethe speaker images are removed, the links to the speakers pages are more prominent, and all of the text on the page is moved into a single column, which is ideal for scrolling down.10Chapter 2

Figure 2-1: The dConstruct website viewed in a desktop browser (left) and a mobile browser (right)

Of course, the Web is appearing on more than just desktop and smartphone devices, and we really need to be working toward an era of websites optimized for any device. I urge you to read Ethan Marcottes article, Responsive Web Design (http://www.alistapart.com/articles/responsive-web-design/), which provides a great introduction to this new paradigm of web design. And if you want to see what other people have been doing with Media Queries theres a great gallery online at http://www.mediaqueri.es/, which showcases some of the better examples of whats possible.

SyntaxA Media Query sets a parameter (or series of parameters) that displays associated style rules if the device used to view the page has properties that match that parameter. You can use Media Queries in three ways, all of which match the different ways that CSS can be applied to a document. The first is to call an external stylesheet using the link element:

The second is to call an external stylesheet using the @import directive:@import url('file') logic media and (expression);

Media Q ueries

11

The third is to use Media Queries in an embedded style element or in the stylesheet itself with the extended @media rule:@media logic media and (expression) { rules }

This method is the one Ill use throughout the rest of this chapter, as its clearer for demonstration purposes. Which method you use will largely depend on your own preference and the demands of your existing stylesheet structure. Now that Ive introduced the declaration methods, lets explore the syntax. You should already be familiar with the media attributeit declares the media types that the styles are applied to, just as in the HTML link tag:

As with the current syntax, you can use a comma-separated list to choose multiple media types. The first new attribute for the @media rule is logic. This optional keyword can have the value of either only or not:@media only media and (expression) { rules } @media not media and (expression) { rules }

The only value is used if you want to hide the rule from older browsers that dont support the syntax; for browsers that do support it, only is effectively ignored. The not value is used to negate the Media Query; you use not to apply the styles if the parameters you set are not met. The next attribute is expression, which is where the main selection takes place. You declare expression by using the and operator and use it to set parameters beyond the media type. These parameters are known as Media Features, and theyre critical to the power of Media Queries. That being the case, lets explore them in detail.

Media FeaturesMedia Features are information about the device thats being used to display the web page: its dimensions, resolution, and so on. This information is used to evaluate an expression, the result of which determines which style rules are applied. That expression could be, for example, apply these styles only on devices that have a screen wider than 480 pixels or only on devices that are orientated horizontally. In Media Queries, most Media Feature expressions require that a value be supplied:@media media and (feature:value) { rules }

12

Chapter 2

This value is required to construct the example expressions I just mentioned. In a few cases, however, the value can be left out and just the existence of the Media Feature itself tested against:@media media and (feature) { rules }

Expressions will become clearer as I talk through the Media Features and explain when values are required or optional. With the syntax covered, lets meet some of the more prominent Media Features. The ones I introduce next are the most applicable to color display screens used for accessing the Web and are the ones youre most likely to use on a day-to-day basis. Other Media Features are available, but theyre more likely to be used for alternative devices such as TVs or fixed-grid terminals.

Width and HeightThe width Media Feature describes the width of the rendering viewport of the specified media type, which, in practice, usually means the current width of the browser (including the scroll bar) for desktop operating systems. The basic syntax requires a length value:@media media and (width:600px) { rules }

In this case, the rules are applied only to browsers that are set to be exactly 600px wide, which is probably far too specific. width also accepts one of two prefixes, however, max- and min-, which allows you to test for a minimum or maximum width:@media media and (max-width:480px) { rules } @media media and (min-width:640px) { rules }

The first query applies the rules in browsers that are no wider than 480px, and the second in browsers that are at least 640px wide. Lets look at a practical example. Here, Ill take advantage of browser window sizes by providing a decorative header for wider windows:@media screen and (min-width: 400px) { h1 { background: black url('landscape.jpg') no-repeat 50% 50%; color: white; height: 189px; margin-bottom: 0; padding: 20px; } }

Media Q ueries

13

This Media Query is testing for browser windows that are at least 400px wide and applying a background image to the h1 element when that is the case. If my browser window is at least 400px wide, I see the image; if I resize it to be narrower, only a text header is shown. You can see this example illustrated in Figure 2-2.

Figure 2-2: Different style rules applied with the width Media Query

The height Media Feature works in the same way, except that it targets browsers based on their height instead of width. The syntax is the same as width and also permits using max- and min- prefixes:@media media and (height:value) { rules } @media media and (max-height:value) { rules } @media media and (min-height:value) { rules }

Because of the prevalence of vertical scrolling, however, height is used much less frequently than width.

14

Chapter 2

Device Width and HeightThe device-width Media Feature functions in a similar way, but it describes the width of the device that is rendering the page. When dealing with web pages, the device width is the width of the screen thats displaying the page rather than the width of the browser window. As with width and height, the basic syntax requires a length value and can be prefixed in the same way:@media media and (device-width:1024px) { rules } @media media and (max-device-width:320px) { rules } @media media and (min-device-width:800px) { rules } device-width becomes most useful when designing for mobile devices, which have smaller display areas. Using this feature, you can cater your designs to those smaller devices without having to create a whole new version of the site designed for the mobile web. For example, Ill optimize some content for display on two different devices. Ill use two boxes of content that, by default, will be floated to sit next to each other on the horizontal plane. For smaller devices (Ill use an iPhone in this example) the boxes will not be floated and, instead, will sit one on top of the other, making better use of the narrower device. Heres the code: .container { width: 500px; } .container div { float: left; margin: 0 15px 0 0; width: 235px; } @media only screen and (max-device-width: 320px) { .container { width: auto; } .container div { float: none; margin: 0; width: auto; } }

By default, I have a 500px container element, with two floated div elements inside it that are 235px wide and have horizontal margins of 15px. Then I create a Media Query (using the only operator to hide it from older browsers) that applies only to devices with a maximum width of 320px (the default iPhone width). This query sets rules that remove the explicit values from the width and margin properties and prevents the boxes from floating. You can see the results in Figure 2-3. The content is more appropriately formatted for its target device, without losing any readability or requiring a special mobile version.

Media Q ueries

15

Figure 2-3: The device-width Media Query displays content differently on a desktop (left) and iPhone (right).

NOTE

iOS (iPhone, iPad, etc.) and Android devices measure device-width by the shorter pair of the four screen sides; that is, given a device with dimensions of 320480, the device-width will be 320px, regardless of whether you're viewing it in portrait or landscape mode. The device-width feature also has a counterpart device-height, which operates as height does to width. Once more, device-height uses a similar syntax, also with max- and min- prefixes:@media media and (device-height:value) { rules } @media media and (max-device-height:value) { rules } @media media and (min-device-height:value) { rules }

Much like height, device-height is used less frequently than device-width because vertical scrolling is easier than horizontal scrolling.

Using Media Queries in the Real WorldIn the examples thus far, Ive tended to create a site that is optimized for larger browsers or devices first, with Media Queries used to provide different styles for smaller (mobile) devices. This has been useful for demonstration purposes, but in your own sites youll probably want to do this the other way round. The reason for this is because of the way that some browsers load page assets, such as images, that are included in stylesheets. Some early adopters of Media Queries would write their code the way weve seen in my examples, using large background images and then setting a value of display: none to hide them from mobile devices. However, those background images can still16Chapter 2

be downloaded and held in the cache even though they arent displayed. This increases the pages load time and can consume bandwidth allowances neither of which is good for mobile device users without wireless connections. A better way to create your pages is to make a basic stylesheet for your mobile audience first and then one with larger assets for desktop or tablet users that is loaded using a Media Query such as device-width:

When the stylesheets are separated in this way, the file desktop.css wont be loaded for devices with a screen width of less than 480px, so none of those large assets will be downloaded in the background. This will work for the great majority of browsers from the past few years; any really old browsers will get the basic stylesheet instead, which is probably better for them as they wont be able to cope with the advanced features Ill be teaching throughout the rest of this book. The big exception to this is Internet Explorer (get used to that sentence; youll be reading it a lot). While IE9 does have Media Query support, previous versions dont. To get around that you just need to load the desktop file using a conditional comment that only Internet Explorer recognizes:

This simply means: If youre using Internet Explorer below version 9, load the file desktop.css. Its a small bit of repetition, but it will solve this problem and let you build your websites in a progressive way.

OrientationIf youre less concerned with the actual dimensions of the viewing device but want to optimize your pages for either horizontal (like a typical web browser) or vertical (like an ebook reader) viewing, the Media Feature you need is orientation. Here is its syntax:@media media and (orientation:value) { rules } value can be one of two options: landscape or portrait. The landscape value applies when the width of your browser is greater than its height, and the portrait value applies when the opposite is true. Although orientation can certainly be applied to desktop browsers, youll find it most useful when dealing with handheld devices that the user can easily rotate, such as the new generation of smartphones and tablets.

Media Q ueries

17

For example, you can use orientation to display a navigation menu horizontally or vertically, depending on the visitors browser orientation. The code looks like this:ul { overflow: hidden; } li { float: left; } @media only screen and (orientation: portrait) { li { float: none; } }

By default, the li elements have a float value of left, making them stack horizontally across the page. If the same page is viewed in a portrait orientationeither by resizing the browser to be taller than it is wide or by viewing the page in a device with a portrait orientationthe float is removed and the li elements stack vertically instead. You can see the result in Figure 2-4.

Figure 2-4: The orientation Media Query on an Android browser: landscape (left) and portrait (right)

As only two values are possible for the orientation feature, if you apply differentiating rules using one value, then the other tacitly becomes the opposite. In this example, I only used the portrait value, so, by default, all of the rules outside of that function apply to the landscape orientation.

Aspect RatioYou can also create queries that apply when a certain width-to-height ratio is met. Use aspect-ratio to test the browsers aspect ratio or device-aspect-ratio to test the devices aspect ratio. Here is the syntax for these two features:@media media and (aspect-ratio:horizontal/vertical) { rules } @media media and (device-aspect-ratio:horizontal/vertical) { rules }

18

Chapter 2

The horizontal and vertical values are positive integers that represent the ratio of the width and height (respectively) of the viewing devices screen, so a square display would be 1/1 and a cinematic widescreen display would be 16/9. Selecting by aspect ratio is potentially fraught with caveats. For example, some device manufacturers define widescreen as 16:9, some as 16:10, and some as 15:10. This variation means you have to include all of these as parameters if you want to apply a widescreen set of rules.

Pixel RatioIn general, the CSS Pixel unit (px) is a measurement of a single pixel on the computer screenif your screen is 1024768 resolution and you give an element a width of 1024px, you expect it to fill the screen horizontally. This is not always the case with smartphone and mobile devices, however. Reading websites on their small screens often involves zooming in, and this magnification causes a screen pixel to be larger than a CSS pixel. For example, magnifying a page by 100 percent means 1 CSS pixel is displayed on the screen by 4 device pixels (22). Magnification is fine for scalable content such as text and vector graphics, but bitmap images can suffer badly from a loss of quality when magnified. To get around this problem, many devices now have screens with higher pixel density ratios, which allow for the display of high-resolution content without any loss of quality. The iPhone 4, for example, has a pixel density of 2, meaning every CSS pixel is displayed on screen by 4 device pixels (as in the example in the previous paragraph), allowing for 100 percent zoom without any loss of detail. A Media Feature is available that lets you target devices based on their pixel density. The feature is device-pixel-ratio, and its implemented in Mobile WebKit with the -webkit- prefix:@media media and (-webkit-device-pixel-ratio: number) { rules }

The number is a decimal that represents the devices pixel density. For example, the Samsung Galaxy S has a pixel density of 1.5; to target screens similar to that, you would use:@media screen and (-webkit-device-pixel-ratio: 1.5) { rules }

As with the other Media Features, you can also detect maximum and minimum pixel ratios:@media media and (-webkit-max-device-pixel-ratio: number) { rules } @media media and (-webkit-min-device-pixel-ratio: number) { rules }

Media Q ueries

19

This flexibility makes serving higher-resolution images to browsers with higher pixel density easier, as you can see in this code:E { background-image: url('image-lores.png'); } @media screen and (-webkit-min-device-pixel-ratio: 1.5) { background-image: url('image-hires.png'); background-size: 100% 100%; }

The first rule ( ) means browsers on devices with a standard (or lowresolution) pixel ratio will use the standard image (image-lores.png), whereas devices with a pixel ratio of at least 1.5 will use the high-resolution image (image-hires.png) instead ( ). Note the use of the background-size property here ( ); this property should be used with high-resolution images to ensure they arent displayed larger than the element they are applied to (I introduce background-size fully in Chapter 8). Pixel ratio detection should also be available in the Firefox Mobile browser (which is still in beta at the time of this writing), albeit with a different syntax for the maximum and minimum media features:@media media and (-moz-device-pixel-ratio: number) { rules } @media media and (max--moz-device-pixel-ratio: number) { rules } @media media and (min--moz-device-pixel-ratio: number) { rules }

Multiple Media FeaturesYou can chain multiple queries together on the same media type by adding expressions with the and operator:@media logic media and (expression) and (expression) { rules }

This syntax tests that both expressions are matched before applying the selected rules. For example, to make sure all permutations of widescreen are covered, as mentioned in the previous section, you would create this query:@media only screen and (aspect-ratio: 15/10) and (aspect-ratio: 16/9) and (aspect-ratio: 16/10) { rules }

You can also set different expressions on multiple media types:@media logic media and (expression), media and (expression) { rules }

Here a different expression would be used for each media type, for example, setting some rules to all landscape devices and portrait projection devices:@media all and (orientation: landscape), projection and (orientation: portrait) { rules }

You can also, of course, create any combination of the above syntaxes.20Chapter 2

Mozilla-Specific Media FeaturesAs part of the work on Firefox Mobile, the Mozilla team has introduced a number of proprietary new media features, many of which are very specific to Gecko (the Firefox rendering engine), but some of which may be proposed to the W3C as official features. You can see all of these at https://developer.mozilla.org/ En/CSS/Media_queries#Mozilla-specific_media_features. Perhaps the most interesting is -moz-touch-enabled, which allows you to apply rules to elements specifically on touchscreen devices, for example, for making buttons bigger to suit fingers rather than a stylus or mouse. Heres the syntax:@media media and (-moz-touch-enabled) { rules }

A device is either touch enabled, in which case it has a value of 1, or isnt, in which case the value is 0. As such, you dont need to state a value parameter and can use the feature keyword only.

SummaryTheir syntax may be simple, but Media Queries have the capacity to be extraordinarily powerful. With the mobile web explosion of recent years, designers and developers are beginning to realize they have the power to tailor their content to the user without employing the old techniques of browser sniffing or separate (and completely different) mobile versions of their sites. Media Queries are already being recognized and hailed by some of the leading lights of web development, and talks are being given about their use at all of the big web conferences. This enthusiasm is largely due to the desire to overcome the constraints of browsing the Web on handheld devices with small screens but is now also being driven by the excitement of early iPad adopters. With careful consideration and clever use of Media Queries, you can create websites that scale perfectly for users, however they access the Web.

Media Queries: Browser SupportWebKit Media Queries Yes Firefox Yes Opera Yes IE No (expected in IE9)

Media Q ueries

21

SELECTORS

Selectors are the heart of CSS, and although the original CSS1 specification had only 5 or 6, CSS2 expanded the range with 12 more. CSS3 goes further still, roughly doubling the number of available selectors.2430

Selectors can be broadly separated into two categories. The first are those that act directly on elements defined in the document tree (p elements and href attributes, for example); this category contains class, type, and attribute selectors. For the sake of expediency, Ill group these together under the banner of DOM selectors. The second category contains pseudo-selectors that act on elements or information that sits outside of the document tree (such as the first letter of a paragraph or the last child of a parent element). Ill cover pseudo-selectors in the next chapterhere Ill discuss DOM selectors. CSS3 provides three new attribute selectors and one new combinatorthat is, a selector that joins other selectors together, such as the child combinator (>) from CSS2. These are defined in the Selectors Level 3 Module (http:// www.w3.org/TR/css3-selectors/), which currently has the status of Proposed Recommendation. This status means the module already has widespread and stable implementation across most browsers (with the current exception of

PX

Internet Explorer, though full support is planned for IE9). The Selectors Level 3 Module is also expected to be one of the first to obtain Candidate Recommendation status. As long as you make provisions for Internet Explorers lack of support, you can start using CSS3 selectors right awaymany sites already do.

Attribute SelectorsAttribute selectors were introduced in CSS2, and, as you may expect from the name, they allow you to specify rules that match elements based on their attributessuch as href or titleand the values of those attributes. The four selectors defined in CSS2 are:E[attr] {} /* Simple Attribut