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

CSS in depth

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


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.



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



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


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.

Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964

Development editor:
Review editor:
Technical development editor:
Project editor:
Copy editor:
Technical proofreader:
Cover designer:

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

Kristen Watterson

Aleksandar Dragosavljevic´
Robin Dewson
Kevin Sullivan
Frances Buran
Elizabeth Martin
Birnou Sébarte
Dennis Dalinnik
Marija Tudor

brief contents



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

Cascade, specificity, and inheritance 3


Working with relative units 28


Mastering the box model


MASTERING LAYOUT ....................................................85

Making sense of floats 87




Grid layout


Positioning and stacking contexts 177


Responsive design 201


CSS AT SCALE ...........................................................231

Modular CSS 233


Pattern libraries 253





ADVANCED TOPICS .....................................................277

Backgrounds, shadows, and blend modes 279


Contrast, color, and spacing 300


Typography 329


Transitions 353


Transforms 370


Animations 396

foreword xv
preface xvii
acknowledgments xix
about this book xxi

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


Cascade, specificity, and inheritance 3

The cascade 4
Understanding stylesheet origin 8 Understanding
specificity 10 Understanding source order 15
Two rules of thumb 17


Inheritance 18
Special values 20
Using the inherit keyword 21


Using the initial keyword

Shorthand properties 23
Beware shorthands silently overriding other styles 23
Understanding the order of shorthand values 24






Working with relative units 28

The power of relative values 29
The struggle for pixel-perfect design
perfect web 29


The end of the pixel-

Ems and rems 31
Using ems to define font-size




Using rems for font-size 36

Stop thinking in pixels 37
Setting a sane default font size 39 Making the panel
responsive 40 Resizing a single component 41


Viewport-relative units 43
Using vw for font size 45


Using calc() for font size 45

Unitless numbers and line-height 46
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

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


Difficulties with element height


Controlling overflow behavior 64 Applying alternatives
to percentage-based heights 65 Using min-height and
max-height 70 Vertically centering content 71


Negative margins 73
Collapsed margins 74
Collapsing between text 74 Collapsing multiple margins
Collapsing outside a container 76


Spacing elements within a container 77
Considering changing content 79
solution: the lobotomized owl selector

Creating a more general




PART 2 MASTERING LAYOUT ..........................................85


Making sense of floats 87

The purpose of floats 88
Container collapsing and the clearfix

Understanding container collapsing 94
the clearfix 96



Unexpected “float catching” 99
Media objects and block formatting contexts 102
Establishing a block formatting context 103 Using a block
formatting context for media object layouts 104


Grid systems 105
Understanding a grid system 106
Adding gutters 111


Building a grid system 107

Flexbox 116


Flexbox principles 117
Building a basic flexbox menu 120
spacing 123


Adding padding and

Flex item sizes 124
Using the flex-basis property 126 Using flex-grow 127
Using flex-shrink 128 Some practical uses 129


Flex direction 130
Changing the flex direction 132


Styling the login form 133

Alignment, spacing, and other details 135
Understanding flex container properties 135 Understanding flex
item properties 139 Using alignment properties 140


A couple of things to be aware of 142
Flexbugs 142


Full-page layout 142

Grid layout 144

Web layout is here 145
Building a basic grid


Anatomy of a grid
Numbering grid lines




Working together with flexbox

Alternate syntaxes 158
Naming grid lines 158

Naming grid areas






Explicit and implicit grid
Adding variety 166

grid track 169




Adjusting grid items to fill the

Feature queries 172
Alignment 175

Positioning and stacking contexts 177

Fixed positioning


Creating a modal dialog with fixed positioning 178
Controlling the size of positioned elements 182


Absolute positioning 182
Absolutely positioning the Close button 182

pseudo-element 183


Positioning a

Relative positioning 185
Creating a dropdown menu 186


Stacking contexts and z-index

Creating a CSS triangle 188


Understanding the rendering process and stacking order 191
Manipulating stacking order with z-index 193 Understanding
stacking contexts 194



Sticky positioning 197

Responsive design 201

Mobile first 202
Creating a mobile menu 209
meta tag 213


Adding the viewport

Media queries 214
Understanding types of media query 215 Adding breakpoints
to the page 217 Adding responsive columns 221


Fluid layouts 223
Adding styles for a large viewport 224


Dealing with tables 226

Responsive images 227
Using multiple images for different viewport sizes 227
Using srcset to serve the correct image 228



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


Modular CSS 233

Base styles: laying the groundwork
A simple module 235
Variations of a module 237
elements 241



Modules with multiple

Modules composed into larger structures 243
Dividing multiple responsibilities among modules 244
Naming modules 248



Utility classes 250
CSS methodologies 251

Pattern libraries 253

Introduction to KSS


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


Shifting the way you build CSS 269
Using a CSS First workflow 269
as an API 270

Using a pattern library

PART 4 ADVANCED TOPICS...........................................277


Backgrounds, shadows,and blend modes 279

Gradients 280
Using multiple color stops 283


Using radial gradients


Shadows 287
Defining depth with gradients and shadows 288 Creating
elements with a flat design 289 Creating buttons with a
more modern look 290


Blend modes 291
Tinting an image 294 Understanding types of
blend mode 295 Adding texture to an image 296
Using mix blend modes 298




Contrast, color, and spacing 300

Contrast is king 302
Establishing patterns 303


Implementing the design


Color 306
Understanding color notations 312 Adding new colors to
a palette 316 Considering contrast for font colors 318




Using ems vs. px 320 Factoring in line height 323
Spacing inline elements 326


Typography 329


Web fonts 331
Google fonts 332
How @font-face works 336
Font formats and fallbacks 337
same typeface 338


Multiple variants of the

Adjusting space for readability 339
Body copy spacing 340
and spacing 342


Headings, small elements,

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

From here to there 354
Timing functions 356
Understanding Bézier curves 357




Non-animatable properties 361
Properties that cannot be animated
and out 365



Transitioning to auto height


Fading in


Transforms 370

Rotate, translate, scale, and skew
Changing the transform origin
transforms 375



Applying multiple




Transforms in motion 375
Scaling up the icon 381 Creating “fly in” labels 383
Staggering the transitions 386


Animation performance 387
Looking at the rendering pipeline 387


Three-dimensional (3D) transforms 389
Controlling perspective
3D transforms 393



Implementing advanced

Animations 396

Keyframes 397
Animating 3D transforms 400
Building the layout without animations
to the layout 405


appendix A
appendix B

Adding animation

Animation delay and fill mode 407
Conveying meaning through animation 409
Responding to user interaction
attention 413




One final piece of advice 416
Selectors reference 417
Preprocessors 422


Drawing the user’s

“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.
Co-founder, CodePen

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.

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

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay