<<

MANNING

Keith J. Grant FOREWORD BY Chris Coyier Box model and border-box sizing

The box model refers to the composition of elements on a page. When you specify the height or width of an element, you’re setting the content size—any padding, border, and margin will be added to that.

Width

Height

Content Padding Border Margin

Applying box-sizing: border-box to an element changes the box model to a more pre- dictable behavior. Setting height or width will control the size of the entire element, including its padding and border.

Width

Height

Content Padding Border Margin

See chapter 3 for information on applying border-box sizing to the entire page, as well as other important concepts including:  Centering content  Creating columns of equal height  Controlling spacing between elements

CSS in Depth

CSS in Depth

KEITH J. GRANT

MANNING SHELTER ISLAND

For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected]

©2018 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.

Manning Publications Co. Development editor: Kristen Watterson 20 Baldwin Road Review editor: Aleksandar Dragosavljevic´ PO Box 761 Technical development editor: Robin Dewson Shelter Island, NY 11964 Project editor: Kevin Sullivan Copy editor: Frances Buran Proofreader: Elizabeth Martin Technical proofreader: Birnou Sébarte Typesetter: Dennis Dalinnik Cover designer: Marija Tudor

ISBN: 9781617293450 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 23 22 21 20 19 18

brief contents

PART 1REVIEWING THE FUNDAMENTALS...... 1

1 ■ Cascade, specificity, and inheritance 3 2 ■ Working with relative units 28 3 ■ Mastering the box model 55

PART 2MASTERING LAYOUT...... 85

4 ■ Making sense of floats 87 5 ■ Flexbox 116 6 ■ Grid layout 144 7 ■ Positioning and stacking contexts 177 8 ■ Responsive design 201

PART 3 CSS AT SCALE ...... 231

9 ■ Modular CSS 233 10 ■ Pattern libraries 253

v

vi BRIEF CONTENTS

PART 4ADVANCED TOPICS...... 277

11 ■ Backgrounds, shadows, and blend modes 279 12 ■ Contrast, color, and spacing 300 13 ■ Typography 329 14 ■ Transitions 353 15 ■ Transforms 370 16 ■ Animations 396

contents

foreword xv preface xvii acknowledgments xix about this book xxi

PART 1REVIEWING THE FUNDAMENTALS...... 1 Cascade, specificity, and inheritance 3 1 1.1 The cascade 4 Understanding stylesheet origin 8 ■ Understanding specificity 10 ■ Understanding source order 15 Two rules of thumb 17 1.2 Inheritance 18 1.3 Special values 20 Using the inherit keyword 21 ■ Using the initial keyword 22 1.4 Shorthand properties 23 Beware shorthands silently overriding other styles 23 Understanding the order of shorthand values 24

vii

viii CONTENTS

Working with relative units 28 2 2.1 The power of relative values 29 The struggle for pixel-perfect design 29 ■ The end of the pixel- perfect web 29 2.2 Ems and rems 31 Using ems to define font-size 32 ■ Using rems for font-size 36 2.3 Stop thinking in pixels 37 Setting a sane default font size 39 ■ Making the panel responsive 40 ■ Resizing a single component 41 2.4 Viewport-relative units 43 Using vw for font size 45 ■ Using calc() for font size 45 2.5 Unitless numbers and line-height 46 2.6 Custom properties (aka CSS variables) 48 Changing custom properties dynamically 50 ■ Changing custom properties with JavaScript 53 ■ Experimenting with custom properties 54

Mastering the box model 55 3 3.1 Difficulties with element width 56 Avoiding magic numbers 59 ■ Adjusting the box model 59 Using universal border-box sizing 61 ■ Adding a gutter between columns 62 3.2 Difficulties with element height 64 Controlling overflow behavior 64 ■ Applying alternatives to percentage-based heights 65 ■ Using min-height and max-height 70 ■ Vertically centering content 71 3.3 Negative margins 73 3.4 Collapsed margins 74 Collapsing between text 74 ■ Collapsing multiple margins 75 Collapsing outside a container 76 3.5 Spacing elements within a container 77 Considering changing content 79 ■ Creating a more general solution: the lobotomized owl selector 80

CONTENTS ix

PART 2MASTERING LAYOUT...... 85 Making sense of floats 87 4 4.1 The purpose of floats 88 4.2 Container collapsing and the clearfix 93 Understanding container collapsing 94 ■ Understanding the clearfix 96 4.3 Unexpected “float catching” 99 4.4 Media objects and block formatting contexts 102 Establishing a block formatting context 103 ■ Using a block formatting context for media object layouts 104 4.5 Grid systems 105 Understanding a grid system 106 ■ Building a grid system 107 Adding gutters 111 Flexbox 116 5 5.1 Flexbox principles 117 Building a basic flexbox menu 120 ■ Adding padding and spacing 123 5.2 Flex item sizes 124 Using the flex-basis property 126 ■ Using flex-grow 127 Using flex-shrink 128 ■ Some practical uses 129 5.3 Flex direction 130 Changing the flex direction 132 ■ Styling the login form 133 5.4 Alignment, spacing, and other details 135 Understanding flex container properties 135 ■ Understanding flex item properties 139 ■ Using alignment properties 140 5.5 A couple of things to be aware of 142 Flexbugs 142 ■ Full-page layout 142 Grid layout 144 6 6.1 Web layout is here 145 Building a basic grid 146 6.2 Anatomy of a grid 148 Numbering grid lines 153 ■ Working together with flexbox 155 6.3 Alternate syntaxes 158 Naming grid lines 158 ■ Naming grid areas 160

x CONTENTS

6.4 Explicit and implicit grid 162 Adding variety 166 ■ Adjusting grid items to fill the grid track 169 6.5 Feature queries 172 6.6 Alignment 175

Positioning and stacking contexts 177 7 7.1 Fixed positioning 178 Creating a modal dialog with fixed positioning 178 Controlling the size of positioned elements 182 7.2 Absolute positioning 182 Absolutely positioning the Close 182 ■ Positioning a pseudo-element 183 7.3 Relative positioning 185 Creating a dropdown menu 186 ■ Creating a CSS triangle 188 7.4 Stacking contexts and z-index 190 Understanding the rendering process and stacking order 191 Manipulating stacking order with z-index 193 ■ Understanding stacking contexts 194 7.5 Sticky positioning 197

Responsive design 201 8 8.1 Mobile first 202 Creating a mobile menu 209 ■ Adding the viewport meta tag 213 8.2 Media queries 214 Understanding types of media query 215 ■ Adding breakpoints to the page 217 ■ Adding responsive columns 221 8.3 Fluid layouts 223 Adding styles for a large viewport 224 ■ Dealing with tables 226 8.4 Responsive images 227 Using multiple images for different viewport sizes 227 Using srcset to serve the correct image 228

CONTENTS xi

PART 3CSS AT SCALE...... 231 Modular CSS 233 9 9.1 Base styles: laying the groundwork 234 9.2 A simple module 235 Variations of a module 237 ■ Modules with multiple elements 241 9.3 Modules composed into larger structures 243 Dividing multiple responsibilities among modules 244 Naming modules 248 9.4 Utility classes 250 9.5 CSS methodologies 251

Pattern libraries 253 10 10.1 Introduction to KSS 254 Setting up KSS 255 ■ Writing KSS documentation 257 Documenting module variants 261 ■ Creating an overview page 264 ■ Documenting modules that require JavaScript 264 Organizing the pattern library into sections 266 10.2 Shifting the way you build CSS 269 Using a CSS First workflow 269 ■ Using a pattern library as an API 270

PART 4ADVANCED TOPICS...... 277

Backgrounds, shadows,and blend modes 279 11 11.1 Gradients 280 Using multiple color stops 283 ■ Using radial gradients 285 11.2 Shadows 287 Defining depth with gradients and shadows 288 ■ Creating elements with a flat design 289 ■ Creating buttons with a more modern look 290 11.3 Blend modes 291 Tinting an image 294 ■ Understanding types of blend mode 295 ■ Adding texture to an image 296 Using mix blend modes 298

xii CONTENTS

Contrast, color, and spacing 300 12 12.1 Contrast is king 302 Establishing patterns 303 ■ Implementing the design 304 12.2 Color 306 Understanding color notations 312 ■ Adding new colors to a palette 316 ■ Considering contrast for font colors 318 12.3 Spacing 320 Using ems vs. px 320 ■ Factoring in line height 323 Spacing inline elements 326

Typography 329 13 13.1 Web fonts 331 13.2 Google fonts 332 13.3 How @font-face works 336 Font formats and fallbacks 337 ■ Multiple variants of the same typeface 338 13.4 Adjusting space for readability 339 Body copy spacing 340 ■ Headings, small elements, and spacing 342 13.5 The dreaded FOUT and FOIT 346 Using Font Face Observer 348 ■ Falling back to system fonts 349 Getting ready for font-display 351

Transitions 353 14 14.1 From here to there 354 14.2 Timing functions 356 Understanding Bézier curves 357 ■ Steps 360 14.3 Non-animatable properties 361 Properties that cannot be animated 364 ■ Fading in and out 365 14.4 Transitioning to auto height 367

Transforms 370 15 15.1 Rotate, translate, scale, and skew 371 Changing the transform origin 374 ■ Applying multiple transforms 375

CONTENTS xiii

15.2 Transforms in motion 375 Scaling up the 381 ■ Creating “fly in” labels 383 Staggering the transitions 386 15.3 Animation performance 387 Looking at the rendering pipeline 387 15.4 Three-dimensional (3D) transforms 389 Controlling perspective 390 ■ Implementing advanced 3D transforms 393 Animations 396 16 16.1 Keyframes 397 16.2 Animating 3D transforms 400 Building the layout without animations 400 ■ Adding animation to the layout 405 16.3 Animation delay and fill mode 407 16.4 Conveying meaning through animation 409 Responding to user interaction 409 ■ Drawing the user’s attention 413 16.5 One final piece of advice 416

appendix A Selectors reference 417 appendix B Preprocessors 422 index 435

foreword

“A minute to learn . . . A lifetime to master.” That phrase might feel a little trite these days, but I still like it. It was popularized in modern times by being the tagline for the board game Othello. In Othello, players take turns placing white or black pieces onto a grid. If, for example, a white piece is played trapping a row of black pieces between two white, all the black pieces are flipped and the row becomes entirely white. Like Othello, it isn’t particularly hard to learn the rules of CSS. You write a selec- tor that attempts to match elements, then you write key/value pairs that style those elements. Even folks just starting out don’t have much trouble figuring out that basic syntax. The trick to getting good at CSS, as in Othello, is knowing exactly when to do what. CSS is one of the languages of the web, but it isn’t quite in the same wheelhouse as programming. CSS has little in the way of logic and loops. Math is limited to a single function. Only recently have variables become a possibility. Rarely do you need to con- sider security. CSS is closer to painting than Python. You’re free to do what you like with CSS. It won’t spit out any errors at you or fail to compile. The journey to getting good at CSS involves learning everything CSS is capable of. The more you know, the more natural it starts to feel. The more you practice, the more easily your brain will reach for that perfect layout and spacing method. The more you read, the more confident you’ll feel in tackling any design. Really good CSS developers aren’t deterred by any design. Every job becomes an opportunity to get clever, a puzzle to be solved. Really good CSS developers have that full and wide spectrum of knowledge of what CSS is capable of. This book is part of

xv

xvi FOREWORD

your journey to being that really good CSS developer. You’ll gain the spectrum of knowledge necessary to getting there. If you’ll permit one more metaphor, despite CSS going on a couple of decades old, it’s a bit like the Wild Wild West. You can do just about whatever you want to do, as long as it’s doing what you want. There aren’t any hard and fast rules. But because you’re all on your own, with no great metrics to tell you if you’re doing a good job— or not—you’ll need to be extra careful. Tiny changes can have huge effects. A stylesheet can grow and grow and become unwieldy. You can start to get scared of your own styles! Keith covers a lot of ground in the book, and every bit of it will help you become a better CSS developer and tame this Wild Wild West. You’ll deep dive into the language itself, learning what CSS is capable of. Then, just as importantly, you’ll learn about ideas around the language that level you up in other ways. You’ll be better at writing code that lasts and is understandable and performant. Even seasoned developers will benefit. If you find yourself reading about some- thing that you already know, you’ll firm up your skills, affirm your knowledge, and find little “oooo” bits that surprise you and extend that base.

CHRIS COYIER Co-founder, CodePen

preface

CSS was proposed in 1994 and first implemented (partially) by Internet Explorer 3 in 1996. It was somewhere around that time I discovered the wonderful View Source but- ton and realized all the secrets of a web page were there for me to decipher in plain text. I taught myself HTML and CSS by playing in a text editor and seeing what worked. It was a fun excuse to spend as much time as possible on the internet. In the meantime, I needed to find a real career. I went on to earn a degree in Com- puter Science. Little did I know that the two would come crashing together in the 2000s as the concept of “web developer” emerged. I’ve been in tune with CSS since the very beginning. Even when I’m working, it’s play. I’ve worked on the back end and the front end, yet I’ve always found myself to be the resident CSS expert on every team I’ve been on. It’s often the most neglected part of the web stack. But once you’ve been on a project with clean CSS, you never want to do without it again. After seeing it in action, even seasoned web developers ask, “How do I learn CSS?” There isn’t one concise, straightforward answer to this question. It’s not a matter of learning one or two quick tips. Rather, you need to understand all the disparate parts of the language and how they can fit together. Some books make a good beginner-level introduction to CSS, but many developers already have a basic understanding. Some books teach a lot of useful tricks but assume the reader has mastery over the language. At the same time, the rate of change in CSS in accelerating. Responsive design is now the de facto standard. Web fonts are commonplace. In 2016, we saw the rise of flexbox, and 2017 began the rise of something called grid layout. Blend modes, box

xvii

xviii PREFACE

shadows, transformations, transitions, and animations are all new to the scene. As more and more browsers become evergreen, automatically updating to the newest ver- sion, new features will continue to roll out. There is a lot to keep up with. Whether you are relatively new to the industry or have been at it a while but need to advance or update your CSS skills, I have written this book to bring you up to speed. Everything in this book is here for one of three reasons: 1 It’s essential. There are many fundamentals of the language that, sadly, many developers don’t fully understand. This includes the cascade, the behavior of floats, and positioning. I’ll take a deep look at them, explaining how they work. 2 It’s new. A lot of new features have emerged in the last few years, or are just emerging now. I will cover the latest improvements to CSS and a few things that are just around the corner. This is a forward-thinking book. I will point out backward compatibility issues where relevant, but I am unabashedly optimistic about the present and future of cross-browser development. 3 It’s not covered in most CSS books. The world of CSS is huge. There are important best practices and common approaches in the modern world of web application development. These are not strictly part of the CSS language, but rather part of its culture. And they are vital for modern web development. So, how do you learn CSS? This book is an attempt to answer that question, for the people who know they need it most.

acknowledgments

It takes an incredible amount of work to produce a book. I believe this is a great book—and hope you’ll agree—but it wouldn’t be nearly as strong as it is without the help of a number of people along the way. First and foremost, I’d like to thank my wife, Courtney. You have been supportive and encouraging through the entire process. You have carried the burden of this book with me. You even provided editorial support in a number of key places. I could not have done this without you. I’d like to acknowledge my boss, Mark Eagle, and the rest of my team at Interconti- nental Exchange. Thank you for encouraging me on the way and allowing me to slip away to write on countless lunch breaks. Thanks to my acquisitions editor, Greg Wild, who found my pathetic first drafts online and reached out to me. And thanks to Manning’s publisher, Marjan Bace, who saw the potential in this idea. There’s always a risk associated in green-lighting a book, particularly with a new author. Thank you for taking that chance. A good book can’t exist without an editor. Thanks to Kristen Watterson for your commitment to quality. This is a much better book because of your input. And thanks to my technical editor, Robin Dewson, for your patience and insight throughout this long process. Thanks to Birnou Sebarté and Louis Lazaris for giving the book a final, thorough technical proofread. Thanks to Chris Coyier for your willingness to write my foreword. I’d also like to thank the technical reviewers and friends who took the time to read through my drafts at various stages and offer feedback: Adam Rackis, Al Pezewski,

xix

xx ACKNOWLEDGMENTS

Amit Lamba, Anto Aravinth, Brian Gaines, Dico Goldoni, Giancarlo Massari, Goetz Heller, Harsh Raval, James Anaipakos, Jeffrey Lim, Jim Arthur, Matthew Halverson, Mitchell Robles, Jr., Nitin Varma, Patrick Goetz, Phily Austria, Pierfrancesco D’Orsogna, Rafael Cassemiro Freire, Rafael Freire, Sachin Singhi, Tanya Wilke, Trent Whiteley, and William E. Wheeler. Your feedback offered valuable early insight into how the book would be received by developers of all skill levels. Finally, I’d like to offer enormous gratitude to the good people on the W3C CSS Working Group for your work on the CSS specifications. You work through a lot of really tough problems so that we developers don’t have to. Thanks for your continued efforts to make CSS, and the web as a whole, better.

about this book

The world of CSS is maturing. More and more web developers in the industry are real- izing that while they “know” CSS, they don’t know it as deeply as they probably should. In recent years, the language has evolved, so even those developers who were once adept at CSS may find a whole new set of skills to catch up on. This book aims to meet both these needs: providing a deep mastery of the language, and bringing you up to speed on recent developments and new features of CSS. This book is titled CSS in Depth, but it is also a book of breadth. Where concepts are difficult or commonly misunderstood, I will explain in detail how they work and why they behave the way they do. In other chapters, I may not exhaust the topic, but I will give you enough knowledge to work effectively with it and point you in the right direc- tion if you wish to further your knowledge. In all, this book will fill in your blind spots. Some of the topics could warrant entire books on their own: animation, typogra- phy, even flexbox and grid layout. My goal is to flesh out your knowledge, help you bolster your weak spots, and give you a love for the language. Who should read this book First and foremost, this book is for developers who are tired of fighting with CSS and are ready to really understand how it works. You may be a beginner, or you may have fifteen years of experience. I expect you to have a cursory understanding of HTML, CSS, and—in a few places—JavaScript. As long as you’re familiar with the basic syntax of CSS, you’ll prob- ably be able to follow along with this book. But it’s primarily written for developers

xxi

xxii ABOUT THIS BOOK

who have spent time with CSS, run into walls, and come out frustrated. In the places where I use JavaScript, I have kept it as simple as possible, so as long as you can follow along with a few short code snippets, you should be in good shape. If instead you’re a designer looking to move into the world of web design, I suspect you too will learn a lot from CSS in Depth—though I haven’t written it with you partic- ularly in mind. The book may also provide some insight into the perspective of the developers you’ll be working with. How this book is organized The book is 16 chapters long, divided into four parts. In part 1, “Reviewing the funda- mentals,” we’ll go back to the basics, with a focus on some details you likely missed the first time around:

■ Chapter 1 covers the cascade and inheritance. These concepts control which styles are applied to which elements on the page. ■ Chapter 2 discusses relative units, with an emphasis on em and rem. Relative units are versatile and important tools in CSS, and this chapter will get you familiar with working with them. ■ Chapter 3 covers the box model. This involves controlling the size of elements on the page and the amount of space between them. In part 2, “Mastering layout,” I’ll walk you through the key tools for laying out ele- ments on the page:

■ Chapter 4 dives into using floats for layout. We’ll build a multicolumn page and look at taming some of the quirky aspects of floats. ■ Chapter 5 teaches flexbox, which is a fairly new layout method. It begins with the fundamental concepts and moves on to practical layout examples. ■ Chapter 6 introduces the brand-new layout tool, grid. It makes possible layouts that have been impossible in CSS until now. ■ Chapter 7 goes deep into positioning using the position property: absolute positioning, fixed positioning, and more. This is an area that gets a lot of devel- opers in trouble, and a solid understanding is essential. ■ Chapter 8 covers responsive design. We’ll look at three key principles to build- ing websites that work on a wide array of screen sizes and device types. In part 3, “CSS at scale,” we’ll look at some more recent best practices. It’s one thing to make the elements look how you want on the page. It’s another thing to organize your code so it can be understood and maintained into the future as your web app grows and evolves. These chapters will teach you some important techniques for man- aging your code:

■ Chapter 9 teaches how to organize your CSS in a modular way, so that your code is reusable and maintainable. ■ Chapter 10 walks you through building a pattern library. This is a vital part of using and maintaining CSS on a team.

ABOUT THIS BOOK xxiii

In part 4, “Advanced topics,” I’ll acquaint you with the world of design. We’ll look at important considerations when working with a designer, and how to do a bit of the design work yourself—because sometimes you will need to:

■ Chapter 11 discusses shadows, gradients, and blend modes. These work together to build an elegant user interface. ■ Chapter 12 shows how to work with contrast, color, and space. Attention to these details goes a long way toward making a good design a great one. ■ Chapter 13 is about web typography: using online font files to bring unique per- sonality to your site or app. ■ Chapter 14 brings motion to the page with transitions, changing the shape, color, or size of an element on the page. ■ Chapter 15 covers transforms, which are a vital tool to use in conjunction with transitions and animations. This chapter also discusses performance implica- tions of motion on the page. ■ Chapter 16 discusses keyframe animations. You’ll learn how to use complex motion to communicate meaning to the user. There are also two appendices:

■ Appendix A is a reference of all the types of CSS selector. ■ Appendix B is an introduction to preprocessors. If you’re not already familiar with preprocessors, you might want to start with this appendix first. I’ve put a lot of effort into the progression of the topics in this book. I start with abso- lute essentials you have to know. From there, the topics build upon one another. In many places, I refer to earlier concepts and work to tie them together when relevant. While I’ve included helpful reference material in places, I encourage you to read the chapters in order. Code conventions and repository This book contains many examples of source code, both in numbered listings and in- line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to high- light code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; I’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. CSS is meant to be paired with HTML; I always provide a code listing for the HTML and another for the CSS. In most chapters, I reuse the same HTML for multiple

xxiv ABOUT THIS BOOK

CSS listings. I guide you through editing a stylesheet in many stages, and I’ve tried to make it clear how I expect you to edit your stylesheet from one CSS listing to the next. Source code for the listings in this book available in a git repository at https:// github.com/CSSInDepth/css-in-depth and on the publisher’s website at https://www .manning.com/books/css-in-depth. At first glance, it may appear that some listings are missing—because working examples require both HTML and CSS, I’ve put most listings in an HTML file, using