📄 Page
1
M A N N I N G Keith J. Grant Foreword by Chris Coyier SECOND EDITION
📄 Page
2
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. Applying box-sizing: border-box to an element changes the box model to a more predict- able behavior. Setting height or width will control the size of the entire element, includ- ing its padding and border. See chapter 3 for more information on applying border box sizing to the entire page, as well as some other important concepts, including centering content and controlling spac- ing between elements. Margin Border Padding Content Height Width Height Width Margin Border Padding Content
📄 Page
3
Praise for the first edition “An incredible way to learn beyond the basic aspects of CSS.” —Andres Sacco, technical leader at TraveleX “If I had to start over learning CSS and could choose only one book, this would be it.” —Seth MacPherson, senior developer at Quote Factory “One of the best, if not the best book for CSS.” —Scott Ling, self-employed contractor “For novices in CSS, this book provides a gradual learning path, while seasoned engineers will find comprehensive coverage of advanced concepts, thoughtfully explained. Ultimately, this book serves as a guide toward mastery.” —Doyle Turner, software engineer at Incremental Systems “The most comprehensive and up-to-date book on CSS. Easily modernize your CSS skills with this painless, progressive training.” —Becky Huett, engineer at Maxar Intelligence
📄 Page
4
(This page has no text content)
📄 Page
5
CSS in Depth, Second Edition KEITH J. GRANT FOREWORD BY CHRIS COYIER MANN I NG SHELTER ISLAND
📄 Page
6
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: orders@manning.com ©2024 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% recycled and processed without the use of elemental chlorine. The authors and publisher have made every effort to ensure that the information in this book was correct at press time. The authors and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Sarah Harter 20 Baldwin Road Technical editor: Chris Chinchilla PO Box 761 Review editors: Isidora Isakov and Radmila Ercegovac Shelter Island, NY 11964 Production editor: Andy Marinkovich Copy editor: Kari Lucke Proofreader: Katie Tennant Technical proofreader: Doyle Turner Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781633437555 Printed in the United States of America
📄 Page
7
v brief contents PART 1 REVIEWING THE FUNDAMENTALS....................................1 1 ■ Cascade, specificity, and inheritance 3 2 ■ Working with relative units 35 3 ■ Document flow and the box model 62 PART 2 MASTERING LAYOUT....................................................91 4 ■ Flexbox 93 5 ■ Grid layout 119 6 ■ Positioning and stacking contexts 153 7 ■ Responsive design 179 PART 3 MODERN CODE ORGANIZATION..................................209 8 ■ Cascade layers and nesting 211 9 ■ Modular CSS and scope 238 10 ■ Container queries 270
📄 Page
8
BRIEF CONTENTSvi PART 4 VISUAL ENHANCEMENTS.............................................291 11 ■ Color and contrast 293 12 ■ Typography and spacing 326 13 ■ Gradients, shadows, and blend modes 357 14 ■ Masks, shapes, and clipping 383 PART 5 ADDING MOTION .......................................................409 15 ■ Transitions 411 16 ■ Transforms 431 17 ■ Animations 459
📄 Page
9
vii contents foreword xv preface xvii acknowledgments xix about this book xxi about the author xxvi about the cover illustration xxvii PART 1 REVIEWING THE FUNDAMENTALS..........................1 1 Cascade, specificity, and inheritance 3 1.1 The cascade 5 Stylesheet origin 8 ■ Inline styles 11 ■ Selector specificity 11 Source order 16 1.2 Inheritance 19 1.3 Special values 21 The inherit keyword 21 ■ The initial keyword 23 ■ The unset keyword 23 ■ The revert keyword 24 1.4 Shorthand properties 25 Beware shorthands silently overriding other styles 25 ■ Remember the order of shorthand values 26
📄 Page
10
CONTENTSviii 1.5 Progressive enhancement 29 Using the cascade for progressive enhancement 29 ■ Progressively enhancing selectors 30 ■ Feature queries using @supports() 31 2 Working with relative units 35 2.1 The power of relative units 36 The rise of responsive design 36 2.2 Ems and rems 37 Using ems to define font-size 39 ■ Using rems for font-size 43 2.3 Stop thinking in pixels 44 Setting a sane default font size 45 ■ Making the panel responsive 47 ■ Resizing a single component 48 2.4 Viewport-relative units 50 Selecting from the newer viewport units 52 ■ Using viewport units for font size 54 2.5 Unitless numbers and line-height 55 2.6 Custom properties (aka CSS variables) 57 Changing custom properties dynamically 59 3 Document flow and the box model 62 3.1 Normal document flow 63 Centering content horizontally 65 ■ Using logical properties 67 Adopting useful shorthand logical properties 69 3.2 The box model 70 Avoiding magic numbers 72 ■ Adjusting the box model 73 Using universal border box sizing 74 3.3 Element height 75 Controlling overflow behavior 75 ■ Using alternatives to percentage-based heights 76 ■ Using min-height and max-height 77 3.4 Negative margins 78 3.5 Collapsed margins 79 Collapsing between text 80 ■ Collapsing multiple margins 80 Collapsing outside a container 81 3.6 Spacing elements within a container 83 Considering changing content 85 ■ Creating a more general solution 86
📄 Page
11
CONTENTS ix PART 2 MASTERING LAYOUT..........................................91 4 Flexbox 93 4.1 Flexbox principles 94 Building a basic flexbox menu 97 ■ Adding padding and spacing 98 4.2 Flex item sizes 100 Flex basis 102 ■ Flex grow 102 ■ Flex shrink 104 Some practical examples 105 4.3 Flex direction 106 Changing the flex direction 108 ■ Styling the login form 109 4.4 Alignment, spacing, and other details 110 Understanding flex container properties 114 ■ Understanding flex item properties 116 ■ Using alignment properties 117 5 Grid layout 119 5.1 Building a basic grid 120 5.2 Anatomy of a grid 122 Numbering grid lines 127 ■ Working together with flexbox 128 5.3 Alternate syntaxes 132 Naming grid lines 132 ■ Naming grid areas 134 5.4 Explicit and implicit grid 136 Adding variety 140 ■ Adjusting grid items to fill the grid track 142 5.5 Subgrid 146 Additional options 150 5.6 Alignment properties 150 6 Positioning and stacking contexts 153 6.1 Fixed positioning 154 Creating a modal dialog with fixed positioning 154 ■ Preventing the screen from scrolling while the modal dialog is open 158 Controlling the size of positioned elements 159 6.2 Absolute positioning 160 Absolutely positioning the Close button 160 ■ Positioning a pseudo-element 161
📄 Page
12
CONTENTSx 6.3 Relative positioning 162 Creating a dropdown menu 163 ■ Creating a CSS triangle 166 6.4 Stacking contexts and z-index 169 Understanding the rendering process and stacking order 169 Manipulating stacking order with z-index 171 ■ Understanding stacking contexts 172 6.5 Sticky positioning 175 7 Responsive design 179 7.1 Mobile first 180 Creating a mobile menu 188 ■ Adding the viewport meta tag 191 7.2 Media queries 192 Understanding types of media queries 194 ■ Adding breakpoints to the page 197 ■ Adding responsive columns 200 7.3 Fluid layouts 202 Adding styles for a large viewport 203 ■ Dealing with tables 204 7.4 Responsive images 206 Using multiple images for different viewport sizes 206 ■ Using srcset to serve the correct image 207 PART 3 MODERN CODE ORGANIZATION........................209 8 Cascade layers and nesting 211 8.1 Manipulating the cascade with layers 212 Defining layers 212 ■ Layer order and priority 216 The revert-layer keyword 219 8.2 A recommended organization for cascade layers 221 Reset layer 221 ■ Theme layer 223 ■ Global layer 224 Layout layer 225 ■ Modules layer 226 ■ Utilities layer 227 Additional layers 228 8.3 The :is() and :where() pseudo-classes 228 More forgiving selectors 229 ■ Manipulating specificity 229 8.4 Nesting 230 Using the nesting selector 231 ■ Understanding the nuances of the nesting selector 233 ■ Nesting media queries and other at-rules 235
📄 Page
13
CONTENTS xi 9 Modular CSS and scope 238 9.1 Defining modules 239 Modules and global styles 240 ■ A simple module 241 Variations of a module 242 ■ Modules with multiple elements 246 9.2 Modules composed into larger structures 249 Dividing multiple responsibilities among modules 250 Naming modules 254 9.3 CSS scope 256 Scope proximity 258 ■ Scoping limit 261 ■ Implicit scope 264 Scope and layers 265 9.4 Pattern libraries 265 Using a CSS-first workflow 266 ■ Refactoring and breaking changes 267 10 Container queries 270 10.1 A basic example of a container query 271 Using container size queries 274 10.2 A closer look at containers 276 Container types 276 ■ Container names 278 ■ Containers and modular CSS 279 10.3 Container-relative units 280 10.4 Container style queries 283 Decoupling a module from its container 284 ■ Reducing code duplication 285 PART 4 VISUAL ENHANCEMENTS...................................291 11 Color and contrast 293 11.1 Communicating with contrast 295 Establishing patterns 296 ■ Implementing the design 297 11.2 Defining color 299 Gamuts and color spaces 306 ■ CSS color notations 308 11.3 Using OKLCH to work with color 313 Switching the stylesheet to OKLCH 315 ■ Naming color variables 316 ■ Selecting new colors for the palette 318 Deriving colors from others on the page 318 11.4 Considering contrast for font colors 323
📄 Page
14
CONTENTSxii 12 Typography and spacing 326 12.1 Spacing 327 Using ems vs. px 327 ■ Factoring in line height 329 Spacing inline elements 333 12.2 Web fonts 335 12.3 Google fonts 337 12.4 How @font-face works 341 Font formats and fallbacks 343 ■ Multiple variants of the same typeface 343 12.5 Performance considerations 344 The font-display property 346 ■ Variable fonts 348 12.6 Adjusting space for readability 350 Body copy spacing 351 ■ Headings, small elements, and spacing 353 13 Gradients, shadows, and blend modes 357 13.1 Gradients 358 Multiple color stops 360 ■ Color interpolation 363 Radial gradients 366 ■ Conic gradients 368 13.2 Shadows 370 Adding depth with gradients and shadows 370 ■ Creating elements with a flat design 372 ■ Creating buttons with a hybrid look 373 13.3 Blend modes 374 Tinting an image 376 ■ Types of blend modes 377 Adding texture to an image 378 ■ Mix blend modes 380 14 Masks, shapes, and clipping 383 14.1 Filters 384 Types of filters 386 ■ Backdrop filter 387 14.2 Masks 389 Masking with a gradient 391 ■ Masking using luminance 392 Other mask properties 393 14.3 Clipping paths 394 Polygon clipping paths 396 ■ Firefox clip-path tools 397 Other clip-path types 399
📄 Page
15
CONTENTS xiii 14.4 Floats and shapes 399 Floating 400 ■ Defining a shape 404 PART 5 ADDING MOTION.............................................409 15 Transitions 411 15.1 From here to there 412 15.2 Timing functions 415 Custom Bézier curves 416 ■ Steps 419 15.3 Non-animatable properties 420 Properties that cannot be animated 423 ■ Fading in and out 424 15.4 Transitioning to auto height 426 15.5 Transitioning custom properties 428 16 Transforms 431 16.1 Rotate, translate, scale, and skew 432 Changing the transform origin 435 ■ Applying multiple transforms 436 ■ Individual transform properties 436 16.2 Transforms in motion 437 Scaling up the icon 443 ■ Creating “fly in” labels 446 Staggering the transitions 448 16.3 Animation performance 449 Looking at the rendering pipeline 449 16.4 3D transforms 451 Controlling perspective 452 ■ Implementing advanced 3D transforms 455 17 Animations 459 17.1 Keyframes 460 17.2 Animating 3D transforms 463 Building the layout without animations 463 ■ Adding animation to the layout 466 17.3 Animation delay and fill mode 468 17.4 Conveying meaning through animation 471 Responding to user interaction 471 ■ Drawing the user’s attention 475
📄 Page
16
CONTENTSxiv 17.5 Scroll-based timelines 477 17.6 One final piece of advice 479 appendix A Selectors reference 481 appendix B Preprocessors 488 index 501
📄 Page
17
xv foreword “A minute to learn, 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 selector that attempts to match elements; then you write key–value pairs that style those ele- ments. Even folks just starting out don’t have much trouble figuring out that basic syn- tax. 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 just a few functions. Only recently have variables become a possibility. Rarely do you need to consider 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 your journey to being that really good CSS developer. You’ll gain the spectrum of knowledge necessary to getting there.
📄 Page
18
FOREWORDxvi If you’ll permit one more metaphor, despite CSS going on a few 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 dive deep 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 “Oh!” bits that surprise you and extend that base. —CHRIS COYIER, cofounder of CodePen
📄 Page
19
xvii 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 backend and the frontend, 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. 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 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 is accelerating. We’ve seen the rise of newer, modern layout methods and effects like blend modes, filters, transformations,
📄 Page
20
PREFACExviii transitions, and animations. Even in the last year or two, logical properties, cascade layers, and container queries have dramatically changed the way we write the lan- guage. 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: It’s essential. There are many fundamentals of the language that, sadly, many developers don’t fully understand. These include the cascade, page layout, and positioning. I’ll take a deep look at these, explaining how they work. It’s new. A lot of new features have emerged in the last few years or are just now emerging. 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 back- ward compatibility issues where relevant, but I am unabashedly optimistic about the future of CSS development, and my goal is to provide you with an under- standing of the language that is ready for emerging changes. 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. It is a com- prehensive guide intended to teach practical proficiency in the language.