Tải bản đầy đủ (.pdf) (428 trang)

CSS Mastery, 3rd Edition_ www.bit.ly/taiho123

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (21.55 MB, 428 trang )

T HE E X P ER T ’S VOIC E ® IN W E B D E V E L O P M E N T

CSS Mastery
Advanced Web Standards Solutions

Third Edition

Andy Budd
Emil Björklund

www.it-ebooks.info


CSS Mastery
Advanced Web Standards Solutions
Third Edition

Andy Budd
Emil Björklund

www.it-ebooks.info


CSS Mastery: Advanced Web Standards Solutions, Third Edition
Andy Budd
Brighton, United Kingdom

Emil Björklund
Malmo, Sweden

ISBN-13 (pbk): 978-1-4302-5863-6



ISBN-13 (electronic): 978-1-4302-5864-3

DOI 10.1007/978-1-4302-5864-3
Library of Congress Control Number: 2016944612
Copyright © 2016 by Andy Budd and Emil Björklund.
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material
is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting,
reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter
developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly
analysis or material supplied specifically for the purpose of being entered and executed on a computer system,
for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only
under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use
must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright
Clearance Center. Violations are liable to prosecution under the respective Copyright Law.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion
and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified
as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither
the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may
be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Managing Director: Welmoed Spahr
Acquisitions Editor: Ben Renow-Clarke
Development Editor: Matthew Moodie
Technical Reviewers: Anna Debenham and Andy Hume
Editorial Board: Steve Anglin, Pramila Balen, Louise Corrigan, James DeWolf, Jonathan Gennick,
Robert Hutchinson, Celestin Suresh John, Nikhil Karkal, James Markham, Susan McDermott,

Matthew Moodie, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing
Coordinating Editor: Nancy Chen
Copy Editor: Bill McManus
Compositor: SPi Global
Indexer: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail ,
or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science +
Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail , or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook
Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary materials referenced by the author in this text is available to readers at
www.apress.com. For detailed information about how to locate your book’s source code, go to
www.apress.com/source-code/.
Printed on acid-free paper

www.it-ebooks.info


This book is dedicated to all my colleagues at Clearleft—both past and present.
Were it not for their support and wisdom, this book would never have happened.
—Andy Budd
Dedicated to the memory of my grandfather: the engineer, artist, and life-long
tinkerer Sven Forsberg (1919–2016).
—Emil Björklund

www.it-ebooks.info



www.it-ebooks.info


Contents at a Glance
About the Authors..................................................................................................xvii
About the Technical Reviewers ..............................................................................xix
Acknowledgments ..................................................................................................xxi
Introduction ..........................................................................................................xxiii
■Chapter 1: Setting the Foundations ....................................................................... 1
■Chapter 2: Getting Your Styles to Hit the Target ..................................................... 17
■Chapter 3: Visual Formatting Model Overview .................................................... 39
■Chapter 4: Web Typography ................................................................................. 61
■Chapter 5: Beautiful Boxes ................................................................................ 101
■Chapter 6: Content Layout ................................................................................. 143
■Chapter 7: Page Layout and Grids ..................................................................... 185
■Chapter 8: Responsive Web Design & CSS......................................................... 223
■Chapter 9: Styling Forms and Data Tables......................................................... 263
■Chapter 10: Making It Move: Transforms, Transitions, and Animations ............ 299
■Chapter 11: Cutting-edge Visual Effects ............................................................ 335
■Chapter 12: Code Quality and Workflow ............................................................ 371
Index ..................................................................................................................... 403

v

www.it-ebooks.info


www.it-ebooks.info



Contents
About the Authors..................................................................................................xvii
About the Technical Reviewers ..............................................................................xix
Acknowledgments ..................................................................................................xxi
Introduction ..........................................................................................................xxiii
■Chapter 1: Setting the Foundations ....................................................................... 1
Structuring your Code ...................................................................................................... 1
Maintainability ........................................................................................................................................ 2
A Brief History of Markup ....................................................................................................................... 2
Progressive Enhancement ...................................................................................................................... 5

Creating Structurally and Semantically Rich HTML .......................................................... 7
Class and ID Attributes ........................................................................................................................... 9
Structural Elements .............................................................................................................................. 10
Using Divs and Spans ........................................................................................................................... 11
Presentational Text Elements, Redefined ............................................................................................. 12
Extending the Semantics of HTML........................................................................................................ 12
Validation .............................................................................................................................................. 15

Summary ........................................................................................................................ 15
■Chapter 2: Getting Your Styles to Hit the Target ..................................................... 17
CSS Selectors ................................................................................................................. 17
Child and Sibling Selectors................................................................................................................... 18
The Universal Selector .......................................................................................................................... 20
Attribute Selectors ................................................................................................................................ 21
Pseudo-Elements.................................................................................................................................. 22

vii


www.it-ebooks.info


■ CONTENTS

Pseudo-Classes .................................................................................................................................... 24
Structural Pseudo-Classes ................................................................................................................... 25
Form Pseudo-Classes ........................................................................................................................... 27

The Cascade ................................................................................................................... 29
Specificity....................................................................................................................... 29
Order of Rules when Resolving the Cascade ........................................................................................ 30
Managing Specificity ............................................................................................................................ 31
Specificity and Debugging .................................................................................................................... 33

Inheritance ..................................................................................................................... 34
Applying Styles to your Document ................................................................................. 35
The Link and Style Elements ................................................................................................................ 35
Performance ......................................................................................................................................... 36

Summary ........................................................................................................................ 38
■Chapter 3: Visual Formatting Model Overview .................................................... 39
Box Model Recap............................................................................................................ 39
Box-Sizing ............................................................................................................................................ 40
Minimum and Maximum Values ........................................................................................................... 44

The Visual Formatting Model .......................................................................................... 44
Anonymous Boxes ................................................................................................................................ 46
Margin Collapsing ................................................................................................................................. 46
Containing Blocks ................................................................................................................................. 48

Relative Positioning .............................................................................................................................. 49
Absolute Positioning ............................................................................................................................. 49
Fixed Positioning .................................................................................................................................. 50
Floating ................................................................................................................................................. 51
Formatting Contexts ............................................................................................................................. 56
Intrinsic and Extrinsic Sizing ................................................................................................................ 58

Other CSS Layout Modules ............................................................................................. 58
Flexible Box Layout............................................................................................................................... 58
Grid Layout ........................................................................................................................................... 59

viii

www.it-ebooks.info


■ CONTENTS

Multi-Column Layout ............................................................................................................................ 59
Regions ................................................................................................................................................. 59

Summary ........................................................................................................................ 59
■Chapter 4: Web Typography ................................................................................. 61
Basic Typesetting in CSS ................................................................................................ 61
Text Color .............................................................................................................................................. 63
Font-Family .......................................................................................................................................... 64
Font Size and Line Height ..................................................................................................................... 65
Line Spacing, Alignment, and the Anatomy of Line Boxes .................................................................... 68
Font Weights ......................................................................................................................................... 70
Font Style.............................................................................................................................................. 71

Transforming Case and Small-Cap Variants ......................................................................................... 71
Changing the Space Between Letters and Words................................................................................. 72

Measure, rhythm, and rag .............................................................................................. 73
Text Indent and Alignment .................................................................................................................... 74
Hyphenation.......................................................................................................................................... 76
Setting Text in Multiple Columns .......................................................................................................... 77

Web Fonts ...................................................................................................................... 81
Licensing .............................................................................................................................................. 82
The @font-face rule.............................................................................................................................. 83
Web Fonts, Browsers, and Performance............................................................................................... 87
Loading Fonts with JavaScript ............................................................................................................. 89

Advanced Typesetting Features...................................................................................... 91
Numerals .............................................................................................................................................. 93
Kerning Options and Text Rendering .................................................................................................... 94

Text Effects ..................................................................................................................... 95
Using and Abusing Text Shadows ......................................................................................................... 95
Using JavaScript to Enhance Typography ............................................................................................. 98

Further Type Inspiration.................................................................................................. 99
Summary ........................................................................................................................ 99
ix

www.it-ebooks.info


■ CONTENTS


■Chapter 5: Beautiful Boxes ................................................................................ 101
Background Color ......................................................................................................... 101
Color Values and Opacity .................................................................................................................... 102

Background Image Basics ............................................................................................ 104
Background Images vs. Content Images ............................................................................................ 105
Simple Example Using Background Images ....................................................................................... 105
Loading Images (and other files) ........................................................................................................ 108
Image Formats.................................................................................................................................... 109

Background Image Syntax ........................................................................................... 109
Background Position........................................................................................................................... 109
Background Clip and Origin ................................................................................................................ 113
Background Attachment ..................................................................................................................... 114
Background Size................................................................................................................................. 115
Background Shorthand ....................................................................................................................... 117

Multiple Backgrounds .................................................................................................. 117
Borders and Rounded Corners ..................................................................................... 119
Border Radius: Rounded Corners........................................................................................................ 119
Creating Circles and Pill Shapes with Border Radius ......................................................................... 122
Border Images .................................................................................................................................... 123

Box-Shadow ................................................................................................................. 125
Spread Radius: Adjusting the Size of the Shadow .............................................................................. 126
Inset Shadows .................................................................................................................................... 126
Multiple Shadows ............................................................................................................................... 127

Using CSS Gradients..................................................................................................... 128

Browser Support and Browser Prefixes.............................................................................................. 129
Linear Gradients ................................................................................................................................. 129
Radial Gradients ................................................................................................................................. 131
Repeating Gradients ........................................................................................................................... 133
Gradients as Patterns ......................................................................................................................... 133

x

www.it-ebooks.info


■ CONTENTS

Styling Embedded Images and other Objects .............................................................. 136
The Flexible Image Pattern ................................................................................................................. 137
New Object-Sizing Methods ............................................................................................................... 138
Aspect-Ratio Aware Flexible Containers ............................................................................................. 139
Reducing Image File Sizes.................................................................................................................. 141

Summary ...................................................................................................................... 142
■Chapter 6: Content Layout ................................................................................. 143
Using Positioning.......................................................................................................... 143
Absolute Positioning Use Cases ......................................................................................................... 144
Positioning and z-index: Stacking Context Pitfalls ............................................................................. 149

Horizontal Layout ......................................................................................................... 150
Using Floats ........................................................................................................................................ 150
Inline Block as a Layout Tool .............................................................................................................. 153
Using Table Display Properties for Layout .......................................................................................... 159
Pros and Cons of the Different Techniques ......................................................................................... 160


Flexbox ......................................................................................................................... 161
Browser Support and Syntax .............................................................................................................. 161
Understanding Flex Direction: Main and Cross Axis ........................................................................... 161
Alignment and Spacing....................................................................................................................... 163
Flexible Sizes ...................................................................................................................................... 168
Wrapping Flexbox Layouts.................................................................................................................. 173
Column Layout and Individual Ordering.............................................................................................. 177
Nested Flexbox Layouts ...................................................................................................................... 180
Flexbox Fallbacks ............................................................................................................................... 182
Flexbox Bugs and Gotchas ................................................................................................................. 183

Summary ...................................................................................................................... 184

xi

www.it-ebooks.info


■ CONTENTS

■Chapter 7: Page Layout and Grids ..................................................................... 185
Planning your Layout .................................................................................................... 185
Grids ................................................................................................................................................... 185
Layout Helper Classes ........................................................................................................................ 187
Using Ready-Made Design Grids and Frameworks ............................................................................ 187
Fixed, Fluid, or Elastic ......................................................................................................................... 188

Creating a Flexible Page Layout ................................................................................... 189
Defining a Content Wrapper................................................................................................................ 191

Row Containers .................................................................................................................................. 193
Creating Columns ............................................................................................................................... 194
Fluid Gutters ....................................................................................................................................... 199
Enhanced Columns: Wrapping and Equal Heights .............................................................................. 204
Flexbox as a General Tool for Page Layout ......................................................................................... 207

The CSS Grid Layout Module: 2D Layout ...................................................................... 209
Understanding the Grid Terminology .................................................................................................. 210
Defining Rows and Columns ............................................................................................................... 211
Placing Items on the Grid ................................................................................................................... 213
Automatic Grid Placement .................................................................................................................. 216
Grid Template Areas ............................................................................................................................ 219

Summary ...................................................................................................................... 222
■Chapter 8: Responsive Web Design & CSS......................................................... 223
A Responsive Example ................................................................................................. 223
Starting Simple ................................................................................................................................... 223
Introducing Our First Media Query ..................................................................................................... 224
Finding Further Breakpoints ............................................................................................................... 226

The Roots of Responsiveness ...................................................................................... 228
Responsive beyond CSS ..................................................................................................................... 229

How Browser Viewports Work ...................................................................................... 230
Nuances of the Viewport Definition .................................................................................................... 230
Configuring the Viewport .................................................................................................................... 232

xii

www.it-ebooks.info



■ CONTENTS

Media Types and Media Queries................................................................................... 234
Media Types ........................................................................................................................................ 234
Media Queries..................................................................................................................................... 234

Structuring CSS for Responsive Design ....................................................................... 237
Mobile First CSS ................................................................................................................................. 238
Where to Place Your Media Queries.................................................................................................... 240

More Responsive Patterns ........................................................................................... 241
Responsive Text Columns ................................................................................................................... 241
Responsive Flexbox without Media Queries ....................................................................................... 242
Responsive Grids with Grid Template Areas ....................................................................................... 244

Going beyond Layout .................................................................................................... 248
Responsive Background Images ........................................................................................................ 248
Responsive Embedded Media ............................................................................................................ 251
Responsive Typography ...................................................................................................................... 257

Summary ...................................................................................................................... 261
■Chapter 9: Styling Forms and Data Tables......................................................... 263
Styling Data Tables ....................................................................................................... 263
Table-Specific Elements ..................................................................................................................... 265
Styling the Table Element ................................................................................................................... 267
Responsive Tables .............................................................................................................................. 270

Styling Forms ............................................................................................................... 274

A simple Form Example ...................................................................................................................... 275
Clear Form Feedback and Help Texts ................................................................................................. 285
Advanced Form Styling ....................................................................................................................... 288

Summary ...................................................................................................................... 298

xiii

www.it-ebooks.info


■ CONTENTS

■Chapter 10: Making It Move: Transforms, Transitions, and Animations ............ 299
How it all Fits Together ................................................................................................. 299
A Note on Browser Support ................................................................................................................ 300

2D Transforms .............................................................................................................. 300
Transform Origin ................................................................................................................................. 303
Translation .......................................................................................................................................... 304
Multiple Transformations .................................................................................................................... 305
Scale and Skew .................................................................................................................................. 307
2D Matrix Transformations ................................................................................................................. 309
Transforms and performance ............................................................................................................. 310

Transitions .................................................................................................................... 311
Transition Timing Functions ................................................................................................................ 313
Different Transitions for Forward and Reverse Directions .................................................................. 316
“Sticky” Transitions ............................................................................................................................ 316
Delayed Transitions............................................................................................................................. 316

What you can and can’t Transition...................................................................................................... 317

CSS Keyframe Animations ............................................................................................ 319
Animating the Illusion of Life .............................................................................................................. 319
Animating Along Curved Lines ............................................................................................................ 323

3D Transforms .............................................................................................................. 326
Getting some Perspective ................................................................................................................... 326
Creating a 3D widget .......................................................................................................................... 328
Advanced Features of 3D Transforms ................................................................................................. 332

Summary ...................................................................................................................... 333

xiv

www.it-ebooks.info


■ CONTENTS

■Chapter 11: Cutting-edge Visual Effects ............................................................ 335
Breaking Out of the Box: CSS Shapes .......................................................................... 337
Inside and Outside Shapes ................................................................................................................. 337

Clipping and Masking ................................................................................................... 344
Clipping............................................................................................................................................... 344
Masking .............................................................................................................................................. 349
Transparent JPEGs with SVG Masking ................................................................................................ 351

Blend Modes and Compositing..................................................................................... 354

Colorizing a Background Image .......................................................................................................... 355
Blending Elements .............................................................................................................................. 357

Image Processing in CSS: Filters.................................................................................. 361
Adjustable Color Manipulation Filters ................................................................................................. 361
Advanced Filters and SVG................................................................................................................... 367

Order of Application for Visual Effects .......................................................................... 369
Summary ...................................................................................................................... 370
■Chapter 12: Code Quality and Workflow ............................................................ 371
Debugging CSS: External Code Quality......................................................................... 371
How Browsers Interpret CSS .............................................................................................................. 372
Optimizing Rendering Performance.................................................................................................... 376

CSS for Humans: Internal Code Quality ........................................................................ 379
Understanding the Shape of CSS........................................................................................................ 380
Code Quality: an Example ................................................................................................................... 381
Managing the Cascade ....................................................................................................................... 384
Structured Naming Schemes and CSS Methodologies ....................................................................... 385
Managing Complexity ......................................................................................................................... 388
Code is for People............................................................................................................................... 391

xv

www.it-ebooks.info


■ CONTENTS

Tooling and Workflow ................................................................................................... 391

Preprocessors and Sass ..................................................................................................................... 391

Workflow Tools ............................................................................................................. 394
Static Analysis and Linters ................................................................................................................. 394
Build Tools .......................................................................................................................................... 395

The Future of CSS Syntax and Structure ...................................................................... 398
Custom Properties—Variables in CSS ................................................................................................ 398
HTTP/2 and Server Push ..................................................................................................................... 399
Web Components................................................................................................................................ 400
CSS and the Extensible Web ............................................................................................................... 401

Summary ...................................................................................................................... 402
Index ..................................................................................................................... 403

xvi

www.it-ebooks.info


About the Authors
Andy Budd is one of the founding partners at digital design consultancy, Clearleft. An early champion of
web standards in the UK, the first edition of this book played a small but important role in the eventual
adoption of CSS. These days, Andy is primarily focused on advancing the field of user experience design.
He does this by consulting with clients, writing articles, mentoring new designers, and speaking at events
like SXSW, An Event Apart, and The Next Web. Andy founded the long running dConstruct conference,
and currently curates the popular UX London conference. In 2011 Andy co-founded the Brighton Digital
Festival, which now sees 40,000 visitors attend 190 events in the city of Brighton each September.
As an active member of the design community, Andy has helped judge a number of international design
awards, and is a mentor at Seedcamp. He is also the driving force behind Silverback, a low-cost usability-testing

tool for the Mac. An avid Twitter user, Andy occasionally finds time to blog at andybudd.com.
Never happier than when he’s diving in some remote tropical atoll, Andy is a qualified PADI dive
instructor and retired shark wrangler.
Emil Björklund is the Technical Director at digital design consultancy
inUse, where he’s usually busy building websites—or helping clients
and co-workers better their craft. Emil created his first HTML page on
Geocities in 1997, but got confused by the mess of table tags. Coming back
to the Web in 2001, he found this magical thing called CSS and has been
fascinated by it ever since.
For the last decade, Emil has been building websites professionally,
hacking on anything from
client-side JavaScript to server-side Python, but always with a special place
in his heart for good old HTML and CSS. Emil’s writing and advice on CSS
has been published in Net Magazine and on CSS Tricks. He also writes
about (mostly) web-related stuff on his blog at thatemil.com.
Emil lives with his girlfriend and their cat in Malmö, Sweden, far from
any sharks.

xvii

www.it-ebooks.info


www.it-ebooks.info


About the Technical Reviewers
Andrew Hume is a web developer from Brighton in the UK. He’s spent the
last fifteen years leading front-end teams for websites like Twitter, Bing,
and The Guardian. As a consultant for Clearleft, he helped figure out large,

scalable CSS systems for clients like the BBC, eBay, and Mozilla.

Anna Debenham is a Freelance Front-end Developer living and working in London in the UK. In 2013,
she was awarded Netmag’s Young Developer of the Year award. She’s the author of Front-end Style Guides,
a Technical Editor for A List Apart, and every December, she co-produces 24 Ways.

xix

www.it-ebooks.info


www.it-ebooks.info


Acknowledgments
We would like to thank the tireless work of Jeffrey Zeldman, Eric Meyer, and Tantek Çelik, without whom the
web standards movement would never have happened. We’d like to thank those who followed. People like
John Allsopp, Rachel Andrew, Mark Boulton, Doug Bowman, Dan Cederholm, Andy Clarke, Simon Collison,
Jon Hicks, Molly E. Holzschlag, Aaron Gustafson, Shaun Inman, Jeremy Keith, Peter-Paul Koch, Ethan
Marcotte, Drew McLellan, Cameron Moll, Dave Shea, Nicole Sullivan, and Jason Santa-Maria, who answered
the challenge and helped take CSS mainstream. Finally, we’d like to thank all those tireless designers and
developers who have subsequently picked up the baton, and have helped turn CSS into the modern design
language we know today. There are too many to list everybody, but some of the people who have made
the biggest impact on our practice in later years include Chris Coyier, Vasilis van Gemert, Stephen Hay, Val
Head, Paul Lewis, Rachel Nabors, Harry Roberts, Lea Verou, Ryan Seddon, Jen Simmons, Sara Soueidan,
Trent Walton, and Estelle Weyl. We’d also like to thank all the designers and developers who constantly help
and inspire us by bouncing ideas about CSS on Twitter and various Slack teams.
We want to thank everybody who helped get this book over the finish line, including inUse who
sponsored part of the work. A special thanks to technical editor Anna Debenham—if there are any errors in
the book, it’s more than likely we put them in there when she was looking the other way. We’d also like to

thank Andy Hume, who contributed his expertise during the early phases of writing, setting the direction
for this new edition. Furthermore, we’d like to thank Charlotte Jackson, Peter-Paul Koch, Paul Lloyd, Mark
Perkins, and Richard Rutter for reading early drafts, bouncing ideas, and giving invaluable feedback.
Photos in the book or in examples are in most instances taken by us or gathered from Public Domain
sources. The following images are licensed via the Creative Commons Attribution 2.0 license (https://
creativecommons.org/licenses/by/2.0/): “Portrait” by Jeremy Keith ( and
“A Long Night Falls on Saturn’s Rings” by NASA Goddard Space Flight Center ( />Finally, we’d both like to thank our partners for patience and support during the considerable time it
took to produce these pages.

xxi

www.it-ebooks.info


www.it-ebooks.info


Introduction
When I started writing the first edition of CSS Mastery way back in 2004, there were already two CSS books
in the market, so I wasn’t sure the world needed a third. After all, CSS was still a relatively niche subject back
then; largely the preserve of bloggers and web standards enthusiasts. The majority of sites were still being
built using tables and frames, and the folks on my local developer mailing list thought I was mad, and CSS
was just a pipe dream. Little did they know we were on the verge of a web standards revolution and the field
exploded around the time the book was published, pushing the book to the top of my publisher’s bestselling
chart for years to come.
By the time the second edition came out, CSS was now firmly established. The role of the book changed
from exposing new people to the power of CSS, to helping make them more efficient and effective. So we
scoured the Web for the latest techniques, workarounds, and hacks, and created a book we hoped would
become the definitive guide for web designers and front-end developers everywhere. It felt like we’d reached
a stable point in the development of the language, and the book would remain relevant for a long time. How

wrong we were.
Rather than becoming stagnant, CSS of recent years feels like it has finally started to live up to its original
promise. We entered the golden age of web standards; an age where browser support was good enough for us
to finally move focus away from hacks, instead putting our efforts into writing elegant, well-crafted, and highly
maintainable code for the largest and most complicated sites around.
So it was time to write a third edition; to bring together all these new tools, techniques, and ways of
thinking into a single reference. To help in this task I drew upon the skills of my good friend, Emil Björklund,
a developer of rare skill and ability. What Emil brings to the book is a deep understanding of modern CSS
practices; how to craft highly flexible code using the latest techniques that works across the widest range of
browsers, screens, and platforms, in the most elegant way possible.
Together we’ve almost completely rewritten the book from the ground up, adding new chapters on web
typography, animation, layout, responsive design, how to structure your code, and much more. This new
edition follows in the footsteps of previous editions, offering a mix of practical examples, language reference,
and cross-browser workarounds for tricky techniques. The sign of CSS mastery is no longer about knowing
all the arcane hacks to make CSS work at all, or knowing all properties by heart. CSS today consists of several
dozen specifications, encompassing hundreds of properties—there’s probably no one who knows it all!
Instead, this book emphasizes flexibility and robustness, making sure your code works in the ever-changing
landscape of different browsers, devices, and usage situations. We won’t cover every single language
feature, but you will find a good overview of what’s available, some lesser-known old-school tricks, and the
occasional glimpse into the future of CSS.
To enjoy the book fully, you should have at least some small grasp of how CSS works—maybe you have
played with it for a while, or even worked on a website or two. The book starts with three short introductory
chapters on the very foundations of creating and styling web pages, so even if you’re rusty, you’ll get a recap.
After that, each chapter introduces new features of the language and progressively more complex examples.
Even if you’re a seasoned CSS practitioner, you should find plenty of interesting and useful techniques for
solving common web design problems, in which case you should feel free to jump to the chapters that pique
your interest.
Regardless of your previous understanding of the language, we hope the resulting book will help you
unlock some of the secrets of CSS and become a true CSS Master.


xxiii

www.it-ebooks.info


CHAPTER 1

Setting the Foundations
The human race is a naturally inquisitive species. We just love tinkering with things. When we got our new
Parrot AR Drone at the office, we had it in pieces before we’d even looked at the instructions. We enjoy
working things out ourselves and creating our own mental models of how we think things behave. We
muddle through and only turn to the manual when something goes wrong or defies our expectations.
One of the best ways to learn Cascading Style Sheets (CSS) is to jump right in and start tinkering.
In fact, this is likely how many of you learned to code; by picking up tips from blogs, viewing source to see
how your favorite designers had achieved a particular effect, and by browsing open source repositories for
snippets of code. You almost certainly didn’t start out by reading the full specification, which is enough to
put anyone to sleep.
Tinkering is a great way to start, but if you’re not careful, you may end up misunderstanding a crucial
concept or building in problems for later on. We know; we’ve done so several times. In this chapter, we’re
going to review some basic but often misunderstood concepts and show you how to keep your HTML and
CSS clear and well structured.
In this chapter you will learn about:


The importance of maintainability



Different versions of HTML and CSS




Strategies for future-friendly and backward-compatible code



Adding meaning to your HTML and using newer HTML5 elements



Adding appropriate styling hooks to HTML



Extending HTML semantics with ARIA, microformats, and microdata



Browser engine modes and validation

Structuring your Code
Most people don’t think about the foundations of a building. However, without solid foundations the
majority of buildings wouldn’t stay standing. While this book is about CSS techniques and concepts,
much of what you are about to learn would not be possible (or at least would be very difficult) without a
well-structured and valid HTML document to work with.
In this section you will learn why well-structured and meaningful HTML is vital to standards-based
development. You will learn how you can add more meaning and flexibility to your documents, and by
doing so, make your job as a developer easier. But first up is a topic of the utmost importance no matter what
language we happen to be working in.
Electronic supplementary material The online version of this chapter (doi:10.1007/978-1-4302-5864-3_1)

contains supplementary material, which is available to authorized users.
© Andy Budd and Emil Björklund 2016
A. Budd and E. Björklund, CSS Mastery, DOI 10.1007/978-1-4302-5864-3_1

www.it-ebooks.info

1


×