CSS in Depth
By Keith Grant
1/5
()
About this ebook
CSS in Depth exposes you to a world of CSS techniques that range from clever to mind-blowing. This instantly useful book is packed with creative examples and powerful best practices that will sharpen your technical skills and inspire your sense of design.
Foreword by Chris Coyier, Cofounder of CodePen.
Dig even deeper into the secrets of CSS with our video course CSS in Depth in Motion, available exclusively at Manning.com (www.manning.com/livevideo/css-in-depth-in-motion)!
Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.
About the Technology
Some websites really pop. They look great, they're visually consistent, and they feel interactive and responsive. You can bet their developers knew CSS in depth. CSS specifies everything from the structural layout of page elements to their individual look and feel. True masters know the patterns of CSS development, the techniques to implement them, and the subtle touches that result in beautiful typography, fluid transitions, and balanced graphics. Join them!
About the Book
CSS in Depth exposes you to a world of CSS techniques that range from clever to mind-blowing. This instantly useful book is packed with creative examples and powerful best practices that will sharpen your technical skills and inspire your sense of design. You'll gain new insights into familiar features like floats and units, and experiment with emerging ideas like responsive design and pattern libraries. Bottom line: this book will make you a better web designer and your apps will look fantastic!
What's Inside
- Avoid common CSS pitfalls
- Master misunderstood concepts
- Use flexbox and grid layout
- Responsive designs for any device
- Code for reuse and maintainability
About the Reader
Written for web developers who know the basics of CSS and HTML.
About the Author
Keith J. Grant is a senior web developer who builds and maintains web applications and websites, including The New York Stock Exchange site.
Table of Contents
-
PART 1 - REVIEWING THE FUNDAMENTALS
- Cascade, specificity, and inheritance
- Working with relative units
- Mastering the box model PART 2 - MASTERING LAYOUT
- Making sense of floats
- Flexbox
- Grid layout
- Positioning and stacking contexts
- Responsive design PART 3 - CSS AT SCALE
- Modular CSS
- Pattern libraries PART 4 - ADVANCED TOPICS
- Backgrounds, shadows, and blend modes
- Contrast, color, and spacing
- Typography
- Transitions
- Transforms
- Animations
Keith Grant
Keith J. Grant is a senior web developer who builds and maintains web applications and websites, including The New York Stock Exchange site.
Read more from Keith Grant
Fruit of the Spirit: Eleven Stories to Transform Your Life Rating: 0 out of 5 stars0 ratingsAndrew Fuller and the Evangelical Renewal of Pastoral Theology Rating: 0 out of 5 stars0 ratings
Related to CSS in Depth
Related ebooks
Secrets of the JavaScript Ninja Rating: 4 out of 5 stars4/5The Joy of JavaScript Rating: 0 out of 5 stars0 ratingsNode.js in Action Rating: 0 out of 5 stars0 ratingsReact in Action Rating: 0 out of 5 stars0 ratingsReact Quickly: Painless web apps with React, JSX, Redux, and GraphQL Rating: 0 out of 5 stars0 ratingsHTML5 in Action Rating: 0 out of 5 stars0 ratingsTypeScript Quickly Rating: 0 out of 5 stars0 ratingsHello! HTML5 & CSS3: A User Friendly Reference Guide Rating: 0 out of 5 stars0 ratingsFunctional Programming in JavaScript: How to improve your JavaScript programs using functional techniques Rating: 0 out of 5 stars0 ratingsSingle Page Web Applications: JavaScript end-to-end Rating: 0 out of 5 stars0 ratingsJavaScript Application Design: A Build First Approach Rating: 0 out of 5 stars0 ratingsWebAssembly in Action: With examples using C++ and Emscripten Rating: 0 out of 5 stars0 ratingsVue.js in Action Rating: 0 out of 5 stars0 ratingsAngular Development with TypeScript Rating: 0 out of 5 stars0 ratingsProgramming with Types: Examples in TypeScript Rating: 0 out of 5 stars0 ratingsExpress in Action: Writing, building, and testing Node.js applications Rating: 4 out of 5 stars4/5React Native in Action: Developing iOS and Android apps with JavaScript Rating: 5 out of 5 stars5/5Web Components in Action Rating: 0 out of 5 stars0 ratingsGet Programming with Node.js Rating: 0 out of 5 stars0 ratingsWeb Performance in Action: Building Fast Web Pages Rating: 0 out of 5 stars0 ratingsIsomorphic Web Applications: Universal Development with React Rating: 0 out of 5 stars0 ratingsGetting MEAN with Mongo, Express, Angular, and Node Rating: 5 out of 5 stars5/5Electron in Action Rating: 0 out of 5 stars0 ratingsGo in Practice Rating: 5 out of 5 stars5/5The Well-Grounded Rubyist Rating: 0 out of 5 stars0 ratingsFlutter in Action Rating: 1 out of 5 stars1/5Dart in Action Rating: 0 out of 5 stars0 ratingsThe Joy of Kotlin Rating: 0 out of 5 stars0 ratingsSeriously Good Software: Code that works, survives, and wins Rating: 5 out of 5 stars5/5Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond Rating: 0 out of 5 stars0 ratings
Programming For You
Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5TensorFlow in 1 Day: Make your own Neural Network Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Photoshop For Beginners: Learn Adobe Photoshop cs5 Basics With Tutorials Rating: 0 out of 5 stars0 ratingsModern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards Rating: 0 out of 5 stars0 ratingsPython QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages Rating: 5 out of 5 stars5/5Programming Arduino: Getting Started with Sketches Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Mastering Windows PowerShell Scripting Rating: 4 out of 5 stars4/5Python Essentials Rating: 5 out of 5 stars5/5
Reviews for CSS in Depth
3 ratings0 reviews
Book preview
CSS in Depth - Keith Grant
Copyright
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
©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.
Development editor: Kristen Watterson
Review editor: Aleksandar Dragosavljević
Technical development editor: Robin Dewson
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 Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Foreword
Preface
Acknowledgments
About this Book
1. Reviewing the fundamentals
Chapter 1. Cascade, specificity, and inheritance
Chapter 2. Working with relative units
Chapter 3. Mastering the box model
2. Mastering layout
Chapter 4. Making sense of floats
Chapter 5. Flexbox
Chapter 6. Grid layout
Chapter 7. Positioning and stacking contexts
Chapter 8. Responsive design
3. CSS at scale
Chapter 9. Modular CSS
Chapter 10. Pattern libraries
4. Advanced topics
Chapter 11. Backgrounds, shadows, and blend modes
Chapter 12. Contrast, color, and spacing
Chapter 13. Typography
Chapter 14. Transitions
Chapter 15. Transforms
Chapter 16. Animations
Appendix A. Selectors reference
Appendix B. Preprocessors
Box model and border-box sizing
Index
List of Figures
List of Tables
List of Listings
Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Foreword
Preface
Acknowledgments
About this Book
1. Reviewing the fundamentals
Chapter 1. Cascade, specificity, and inheritance
1.1. The cascade
1.1.1. Understanding stylesheet origin
1.1.2. Understanding specificity
1.1.3. Understanding source order
1.1.4. Two rules of thumb
1.2. Inheritance
1.3. Special values
1.3.1. Using the inherit keyword
1.3.2. Using the initial keyword
1.4. Shorthand properties
1.4.1. Beware shorthands silently overriding other styles
1.4.2. Understanding the order of shorthand values
Summary
Chapter 2. Working with relative units
2.1. The power of relative values
2.1.1. The struggle for pixel-perfect design
2.1.2. The end of the pixel-perfect web
2.2. Ems and rems
2.2.1. Using ems to define font-size
2.2.2. Using rems for font-size
2.3. Stop thinking in pixels
2.3.1. Setting a sane default font size
2.3.2. Making the panel responsive
2.3.3. Resizing a single component
2.4. Viewport-relative units
2.4.1. Using vw for font size
2.4.2. Using calc() for font size
2.5. Unitless numbers and line-height
2.6. Custom properties (aka CSS variables)
2.6.1. Changing custom properties dynamically
2.6.2. Changing custom properties with JavaScript
2.6.3. Experimenting with custom properties
Summary
Chapter 3. Mastering the box model
3.1. Difficulties with element width
3.1.1. Avoiding magic numbers
3.1.2. Adjusting the box model
3.1.3. Using universal border-box sizing
3.1.4. Adding a gutter between columns
3.2. Difficulties with element height
3.2.1. Controlling overflow behavior
3.2.2. Applying alternatives to percentage-based heights
3.2.3. Using min-height and max-height
3.2.4. Vertically centering content
3.3. Negative margins
3.4. Collapsed margins
3.4.1. Collapsing between text
3.4.2. Collapsing multiple margins
3.4.3. Collapsing outside a container
3.5. Spacing elements within a container
3.5.1. Considering changing content
3.5.2. Creating a more general solution: the lobotomized owl selector
Summary
2. Mastering layout
Chapter 4. Making sense of floats
4.1. The purpose of floats
4.2. Container collapsing and the clearfix
4.2.1. Understanding container collapsing
4.2.2. Understanding the clearfix
4.3. Unexpected float catching
4.4. Media objects and block formatting contexts
4.4.1. Establishing a block formatting context
4.4.2. Using a block formatting context for media object layouts
4.5. Grid systems
4.5.1. Understanding a grid system
4.5.2. Building a grid system
4.5.3. Adding gutters
Summary
Chapter 5. Flexbox
5.1. Flexbox principles
5.1.1. Building a basic flexbox menu
5.1.2. Adding padding and spacing
5.2. Flex item sizes
5.2.1. Using the flex-basis property
5.2.2. Using flex-grow
5.2.3. Using flex-shrink
5.2.4. Some practical uses
5.3. Flex direction
5.3.1. Changing the flex direction
5.3.2. Styling the login form
5.4. Alignment, spacing, and other details
5.4.1. Understanding flex container properties
5.4.2. Understanding flex item properties
5.4.3. Using alignment properties
5.5. A couple of things to be aware of
5.5.1. Flexbugs
5.5.2. Full-page layout
Summary
Chapter 6. Grid layout
6.1. Web layout is here
6.1.1. Building a basic grid
6.2. Anatomy of a grid
6.2.1. Numbering grid lines
6.2.2. Working together with flexbox
6.3. Alternate syntaxes
6.3.1. Naming grid lines
6.3.2. Naming grid areas
6.4. Explicit and implicit grid
6.4.1. Adding variety
6.4.2. Adjusting grid items to fill the grid track
6.5. Feature queries
6.6. Alignment
Summary
Chapter 7. Positioning and stacking contexts
7.1. Fixed positioning
7.1.1. Creating a modal dialog with fixed positioning
7.1.2. Controlling the size of positioned elements
7.2. Absolute positioning
7.2.1. Absolutely positioning the Close button
7.2.2. Positioning a pseudo-element
7.3. Relative positioning
7.3.1. Creating a dropdown menu
7.3.2. Creating a CSS triangle
7.4. Stacking contexts and z-index
7.4.1. Understanding the rendering process and stacking order
7.4.2. Manipulating stacking order with z-index
7.4.3. Understanding stacking contexts
7.5. Sticky positioning
Summary
Chapter 8. Responsive design
8.1. Mobile first
8.1.1. Creating a mobile menu
8.1.2. Adding the viewport meta tag
8.2. Media queries
8.2.1. Understanding types of media query
8.2.2. Adding breakpoints to the page
8.2.3. Adding responsive columns
8.3. Fluid layouts
8.3.1. Adding styles for a large viewport
8.3.2. Dealing with tables
8.4. Responsive images
8.4.1. Using multiple images for different viewport sizes
8.4.2. Using srcset to serve the correct image
Summary
3. CSS at scale
Chapter 9. Modular CSS
9.1. Base styles: laying the groundwork
9.2. A simple module
9.2.1. Variations of a module
9.2.2. Modules with multiple elements
9.3. Modules composed into larger structures
9.3.1. Dividing multiple responsibilities among modules
9.3.2. Naming modules
9.4. Utility classes
9.5. CSS methodologies
Summary
Chapter 10. Pattern libraries
10.1. Introduction to KSS
10.1.1. Setting up KSS
10.1.2. Writing KSS documentation
10.1.3. Documenting module variants
10.1.4. Creating an overview page
10.1.5. Documenting modules that require JavaScript
10.1.6. Organizing the pattern library into sections
10.2. Shifting the way you build CSS
10.2.1. Using a CSS First workflow
10.2.2. Using a pattern library as an API
Summary
4. Advanced topics
Chapter 11. Backgrounds, shadows, and blend modes
11.1. Gradients
11.1.1. Using multiple color stops
11.1.2. Using radial gradients
11.2. Shadows
11.2.1. Defining depth with gradients and shadows
11.2.2. Creating elements with a flat design
11.2.3. Creating buttons with a more modern look
11.3. Blend modes
11.3.1. Tinting an image
11.3.2. Understanding types of blend mode
11.3.3. Adding texture to an image
11.3.4. Using mix blend modes
Summary
Chapter 12. Contrast, color, and spacing
12.1. Contrast is king
12.1.1. Establishing patterns
12.1.2. Implementing the design
12.2. Color
12.2.1. Understanding color notations
12.2.2. Adding new colors to a palette
12.2.3. Considering contrast for font colors
12.3. Spacing
12.3.1. Using ems vs. px
12.3.2. Factoring in line height
12.3.3. Spacing inline elements
Summary
Chapter 13. Typography
13.1. Web fonts
13.2. Google fonts
13.3. How @font-face works
13.3.1. Font formats and fallbacks
13.3.2. Multiple variants of the same typeface
13.4. Adjusting space for readability
13.4.1. Body copy spacing
13.4.2. Headings, small elements, and spacing
13.5. The dreaded FOUT and FOIT
13.5.1. Using Font Face Observer
13.5.2. Falling back to system fonts
13.5.3. Getting ready for font-display
Summary
Chapter 14. Transitions
14.1. From here to there
14.2. Timing functions
14.2.1. Understanding Bézier curves
14.2.2. Steps
14.3. Non-animatable properties
14.3.1. Properties that cannot be animated
14.3.2. Fading in and out
14.4. Transitioning to auto height
Summary
Chapter 15. Transforms
15.1. Rotate, translate, scale, and skew
15.1.1. Changing the transform origin
15.1.2. Applying multiple transforms
15.2. Transforms in motion
15.2.1. Scaling up the icon
15.2.2. Creating fly in
labels
15.2.3. Staggering the transitions
15.3. Animation performance
15.3.1. Looking at the rendering pipeline
15.4. Three-dimensional (3D) transforms
15.4.1. Controlling perspective
15.4.2. Implementing advanced 3D transforms
Summary
Chapter 16. Animations
16.1. Keyframes
16.2. Animating 3D transforms
16.2.1. Building the layout without animations
16.2.2. Adding animation to the layout
16.3. Animation delay and fill mode
16.4. Conveying meaning through animation
16.4.1. Responding to user interaction
16.4.2. Drawing the user’s attention
16.5. One final piece of advice
Summary
Appendix A. Selectors reference
A.1. Basic selectors
A.2. Combinators
Compound selectors
A.3. Pseudo-class selectors
A.4. Pseudo-element selectors
A.5. Attribute selectors
Case-insensitive attribute selectors
Appendix B. Preprocessors
B.1. Sass
B.1.1. Installing Sass
B.1.2. Running Sass
B.1.3. Understanding important Sass features
B.2. PostCSS
B.2.1. Using Autoprefixer
B.2.2. Using cssnext
B.2.3. Using cssnano
B.2.4. Using PreCSS
Box model and border-box sizing
Index
List of Figures
List of Tables
List of Listings
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 selector 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 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.
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 something 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 button 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 Computer 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 shadows, transformations, transitions, and animations are all new to the scene. As more and more browsers become evergreen, automatically updating to the newest version, 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:
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.
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.
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 Intercontinental 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, 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 realizing 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 direction 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, typography, 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 probably be able to follow along with this book. But it’s primarily written for developers 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 particularly 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 fundamentals,
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 elements 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 developers in trouble, and a solid understanding is essential.
Chapter 8 covers responsive design. We’ll look at three key principles to building 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 managing 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.
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 personality 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 implications 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 absolute 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 inline 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 highlight 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 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
For example, in chapter 1, listing 1.1 is HTML code and listing 1.2 is CSS that is meant to be applied to that HTML. I have included both in the repository in a file named listing-1.2.html. Changes are made to this CSS in listing 1.3; these are included in listing-1.3.html, along with the corresponding HTML from listing 1.1.
Browser versions
Cross-browser testing is an important part of web development. Most of the code in this book is supported in IE 10 and 11, Microsoft Edge, Chrome, Firefox, Safari, Opera, and most mobile browsers. Newer features will not work in all of these browsers; I indicate when this is the case.
Just because a feature is not supported in a particular browser doesn’t mean you can’t use it. You can often provide fallback behavior for the older browsers as an acceptable compromise. I show examples of this in many places.
If you’re following along with the code examples on your computer, I recommend you use the latest version of Firefox or Chrome.
Note to print book readers
Many graphics in this book are meant to be viewed in color. The eBook versions display the color graphics, so they should be referred to as you read. To get your free eBook in PDF, ePub, and Kindle formats, go to https://www.manning.com/freebook and follow the instructions to complete your pBook registration.
Book forum
Purchase of CSS in Depth includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://forums.manning.com/forums/css-in-depth. You can also learn more about Manning’s forums and the rules of conduct at https://forums.manning.com/forums/about.
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
About the author
Keith J. Grant is currently a senior web developer at Intercontinental Exchange, Inc. (ICE), where he wrote and maintains the CSS, both for the corporate and for the New York Stock Exchange websites. He has 11 years of professional experience building and maintaining web applications and websites using HTML, CSS, and JavaScript. He is self-taught in HTML and CSS, and he has several more years of informal experience working with the technology.
His manager brought him onto the website team expressly for his expertise in CSS, when ICE needed to implement a redesign of the websites. CSS enables companies to brand their sites in unique and creative ways, and to offer complex web applications with intricate layouts.
Though Keith has primarily been a JavaScript developer, he has become a very important CSS instructor at every company he’s worked for.
About the cover illustration
The figure on the cover of CSS in Depth is taken from a nineteenth-century collection of works by many artists, edited by Louis Curmer and published in Paris in 1841. The title of the collection is Les Français peints par euxmêmes, which translates as The French People Painted by Themselves. Each illustration is finely drawn and colored by hand, and the rich variety of drawings in the collection reminds us vividly of how culturally apart the world’s regions, towns, villages, and neighborhoods were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress.
Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns or regions. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technological life.
At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by pictures from collections such as this one.
Part 1. Reviewing the fundamentals
Part 1 takes a deep look into the most essential parts of CSS—the cascade, relative units, and the box model. These fundamentals, covered in these first three chapters, control what styles are applied to the elements on the page and how the sizes of those elements are determined. A comprehensive understanding of these subjects is foundational to everything else in this book and beyond.
Chapter 1. Cascade, specificity, and inheritance
This chapter covers
The four parts that make up the cascade
The difference between the cascade and inheritance
How to control which styles apply to which elements
Common misunderstandings about shorthand declarations
CSS is unlike a lot of things in the world of software development. It’s not a programming language, strictly speaking, but it does require abstract thought. It’s not purely a design tool, but it does require some creativity. It provides a deceptively simple declarative syntax, but if you’ve worked with it on any large projects, you know it can grow into unwieldy complexity.
When you need to learn to do something in conventional programming, you can usually figure out what to search for (for example, "How do I find items of type x in an array?). With CSS, it’s not always easy to distill the problem down to a single question. Even when you can, the answer is often
it depends." The best way to accomplish something is often contingent on your particular constraints and how precisely you’ll want to handle various edge cases.
While it’s helpful to know some tricks
or useful recipes you can follow, mastering CSS requires an understanding of the principles that make those practices possible. This book is full of examples, but it is primarily a book of principles.
Part 1 begins with the most fundamental principles of the language: the cascade, the box model, and the wide array of unit types available. Most web developers know about the cascade and the box model. They know about pixel units and may have heard that they should use ems instead.
The truth is, there’s a lot to these topics, and a cursory understanding of them gets you only so far. If you’re ever to master CSS, you must first know the fundamentals, and know them deeply.
I know you’re excited to start learning the latest and greatest CSS has to offer. That is the exciting stuff. But first, we’ll go back to the fundamentals. I’ll quickly review the basics, which you’re likely already familiar with, and then dive deep into each topic. My aim is to strengthen the foundation on which the rest of your CSS is built.
In this chapter, we begin with the C in CSS—the cascade. I’ll articulate how it works, then show you how to work with it practically. We then look at a related topic, inheritance. I’ll follow that with a look at shorthand properties and some common misunderstandings surrounding them.
Together, these topics are all about applying the styles you want to the elements you want. There’s a lot of gotchas
here that often trip up developers. A good understanding of these topics will give you better control over making your CSS do what you want it to do. With any luck, you’ll also better appreciate and even enjoy working with CSS.
1.1. The cascade
Fundamentally, CSS is about declaring rules: Under various conditions, we want certain things to happen. If this class is added to that element, apply these styles. If element X is a child of element Y, apply those styles. The browser then takes these rules, figures out which ones apply where, and uses them to render the page.
When you look at small examples, this process is usually straightforward. But as your stylesheet grows, or the number of pages you apply it to increases, your code can become complex surprisingly quickly. There are often several ways to accomplish the same thing in CSS. Depending on which solution you use, you may get wildly different results when the structure of the HTML changes, or when the styles are applied to different pages. A key part of CSS development comes down to writing rules in such a way that they’re predictable.
The first step toward this is understanding how exactly the browser makes sense of your rules. Each rule may be straightforward on its own, but what happens when two rules provide conflicting information about how to style an element? You may find one of your rules doesn’t do what you expect because another rule conflicts with it. Predicting how rules behave requires an understanding of the cascade.
To illustrate, you’ll build a basic page header like one you might see at the top of a web page (figure 1.1). It has the website title atop a series of teal navigational links. The last link is colored orange to make it stand out as a sort of featured link.
Figure 1.1. Page heading and navigation links
Note to print book readers
Many graphics in this book are meant to be viewed in color. The eBook versions display the color graphics, so they should be referred to as you read. To get your free eBook in PDF, ePub, and Kindle formats, go to https://www.manning.com/books/css-in-depth to register your print book.
As you build this page header, you’ll probably be familiar with most of the CSS involved. This will allow us to focus on aspects of CSS you might take for granted or only partially understand.
To begin, create an HTML document and a stylesheet named styles.css. Add the code in listing 1.1 to the HTML.
Note
A repository containing all code listings in this book is available for download at https://github.com/CSSInDepth/css-in-depth. The repository has all CSS embedded with the corresponding HTML in a series of HTML files.
Listing 1.1. Markup for the page header
styles.css rel=stylesheet
type=text/css
/>
page-title class=title
>Wombat Coffee Roasters
1
- main-nav class=
nav>
2
featured>Specials
3
1 Page title
2 List of navigation links
3 Featured link
When two or more rules target the same element on your page, the rules may provide conflicting declarations. The next listing shows how this is possible. It shows three rulesets, each specifying a different font style for the page title. The title can’t have three different fonts at one time. Which one will it be? Add this to your CSS file to see.
Listing 1.2. Conflicting declarations
h1 { 1
font-family: serif;
}
#page-title {
2
font-family: sans-serif;
}
.title {
3
font-family: monospace;
}
1 Tag (or type) selector
2 ID selector
3 Class selector
Rulesets with conflicting declarations can appear one after the other, or they can be scattered throughout your stylesheet. Either way, given your HTML, they all target the same element.
All three rulesets attempt to set a different font family to this heading. Which one will win? To determine the answer, the browser follows a set of rules, so the result is predictable. In this case, the rules dictate that the second declaration, which has an ID selector, wins; the title will have a sans-serif font (figure 1.2).
Figure 1.2. The ID selector wins over the other rulesets, producing a sans-serif font for the title.
The cascade is the name for this set of rules. It determines how conflicts are resolved, and it’s a fundamental part of how the language works. Although most experienced developers have a general sense of the cascade, parts of it are sometimes misunderstood.
Let’s unpack the cascade. When declarations conflict, the cascade considers three things to resolve the difference:
Stylesheet origin—Where the styles come from. Your styles are applied in conjunction with the browser’s default styles.
Selector specificity—Which selectors take precedence over which.
Source order—Order in which styles are declared in the stylesheet.
The rules of the cascade are considered in this order. Figure 1.3 shows how they’re applied at a higher level.
Figure 1.3. High-level flowchart of the cascade showing declaration precedence
These rules allow browsers to behave predictably when resolving any ambiguity in the CSS. Let’s step through them one at a time.
1.1.1. Understanding stylesheet origin
The stylesheets you add to your web page aren’t the only ones the browser applies. There are different types, or origins, of stylesheets. Yours are called author styles; there are also user agent styles, which are the browser’s default styles. User agent styles have lower priority, so your styles override them.
Note
Some browsers let users define a user stylesheet. This is considered a third origin, with a priority between user agent and author styles. User styles are rarely used and beyond your control, so I’ve left them out for simplicity.
User agent styles vary slightly from browser to browser, but generally they do the same things: headings (
through
) and paragraphs (
) are given a top and bottom margin, lists (
- and
- ) are given a left padding, and link colors and default font sizes are set.
A quick review of terminology
Depending on where you learned CSS, you may or may not be familiar with all the names of the various parts of CSS syntax. I won’t belabor the point, but because I’ll be using these terms throughout the book, it’s best to be clear about what they mean.
Following is a line of CSS. This is called a declaration. This declaration is made up of a property (color) and a value (black):
color: black;
Properties aren’t to be confused with attributes, which are part of the HTML syntax. For example, in the element />, href is an attribute of the a tag.
A group of declarations inside curly braces is called a declaration block. A declaration block is preceded by a selector (in this case, body):
body {
color: black;
font-family: Helvetica;
}
Together, the selector and declaration block are called a ruleset. A ruleset is also called a rule—although, it’s my observation that rule is rarely used so precisely and is usually used in the plural to refer to a broader set of styles.
Finally, at-rules are language constructs beginning with an at
symbol, such as @import rules or @media queries.
User agent styles
Let’s look again at the example page (figure 1.4). The title is sans-serif because of the styles you added. A number of other things are determined by the user agent styles: the list has a left padding and a list-style-type of disc to produce the bullets. Links are blue and underlined. The heading and the list have top and bottom margins.
Figure 1.4. User agent styles set defaults for your web page header.
After user agent styles are considered, the browser applies your styles—the author styles. This allows declarations you specify to override those set by the user agent stylesheet. If you link to several stylesheets in your HTML, they all have the same origin: the author.
The user agent styles set things you typically want, so they don’t do anything entirely unexpected. When you don’t like what they do to a certain property, set your own value in your stylesheet. Let’s do that now. You can override some of the user agent styles that aren’t what you want so your page will look like figure 1.5.
Figure 1.5. Author styles override user agent styles because they have higher priority.
In the following listing, I’ve removed the conflicting font-family declarations from the earlier example and added new ones to set colors and override the user agent margins and the list padding and bullets. Edit your stylesheet to match these changes.
Listing 1.3. Overriding user agent styles
h1 {
color: #2f4f4f;
margin-bottom: 10px;
1
}
#main-nav {
margin-top: 10px;
1
list-style: none;
2
padding-left: 0;
2
}
#main-nav li {
display: inline-block;
3
}
#main-nav a {
color: white;
4
background-color: #13a4a4;
4
padding: 5px;
4
border-radius: 2px;
4
text-decoration: none;
4
}
1 Reduces the margins
2 Removes user agent list styles
3 Makes list items appear side by side rather than stacked
4 Provides a button-like appearance for the navigational links
If you’ve worked with CSS for long, you’re probably used to overriding user agent styles. When you do, you’re using the origin part of the cascade. Your styles will always override the user agent styles because the origins are different.
Note
You may notice I used ID selectors in this code. There are reasons to avoid doing this, which I’ll cover in a bit.
Important declarations
There’s an exception to the style origin rules: declarations that are marked as important. A declaration can be marked important by adding !important to the end of the declaration, before the semicolon:
color: red !important;
Declarations marked !important are treated as a higher-priority origin, so the overall order of preference, in decreasing order, is this:
Author important
Author
User agent
The cascade independently resolves conflicts for every property of every element on the page. For instance, if you set a bold font on a paragraph, the top and bottom margin from the user agent stylesheet still applies (unless you explicitly override them). The concept of style origin will come into play when we get to transitions and animations because they introduce more origins to this list. The !important annotation is an interesting quirk of CSS, which we’ll come back to again shortly.