Statistics
4
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-10

AuthorTiffany B Brown

CSS Masteris tailor-made for the web designer or front-end devleoper who's really serious about taking their skills to the next level. Discover how to keep ahead of the game by adhering to best practice and employing the most effective, cutting-edge CSS techniques. Now thoroughly updated in its second edition, this book covers how to: Organize your CSS to create the most efficient and most maintainable code Employ advanced approaches to achieve complex layouts: flexbox, grid layouts, multi-column, and more Use next-level effects: transitions, transforms, filters, animations, and more Combine CSS and SVG to create seriously powerful visuals Use efficient debugging techniques And much more!

Tags
No tags
ISBN: 0648331504
Publisher: Sitepoint
Publish Year: 2018
Language: 英文
Pages: 354
File Format: PDF
File Size: 29.4 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
CSS Master, 2nd Edition Copyright © 2018 SitePoint Pty. Ltd. Product Manager: Simon Mackie Technical Editor: Rachel Andrew English Editor: Ralph Mason Cover Designer: Alex Walker Notice of Rights All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews. Notice of Liability The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software or hardware products described herein. Trademark Notice Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark. Published by SitePoint Pty. Ltd. 48 Cambridge Street Collingwood VIC Australia 3066 Web: www.sitepoint.com Email: books@sitepoint.com ISBN 978-0-6483315-0-6 (print) ISBN 978-1-925836-16-5 (ebook) Printed and bound in the United States of America i
About Tiffany B. Brown Tiffany B. Brown is a freelance web developer based in Los Angeles, California. She has worked on the web for nearly two decades with a career that includes media companies, marketing agencies, and government. Brown was also part of the Digital Service Team at the United States Department of Veterans Affairs, the United States Digital Service, and the Opera Software Developer Relations team. Brown is also a co-author of SitePoint's Jump Start: HTML 5, and has contributed to Dev.Opera, A List Apart, SitePoint.com, and Smashing Magazine. About SitePoint SitePoint specializes in publishing fun, practical, and easy-to-understand content for web professionals. Visit http://www.sitepoint.com/ to access our blogs, books, newsletters, articles, and community forums. You’ll find a stack of information on JavaScript, PHP, Ruby, mobile development, design, and more. 2 CSS Master
Table of Contents Preface ......................................................................................................................... vii Who Should Read This Book? ................................................................................... viii Conventions Used ........................................................................................................... viii Supplementary Materials................................................................................................ix Chapter 1: CSS Architecture and Organization ............10 File Organization ................................................................................................................11 Specificity ............................................................................................................................. 13 Choosing What to Name Things ...............................................................................26 Atomic CSS ..........................................................................................................................30 Conclusion ...........................................................................................................................34 Chapter 2: Debugging and Optimization............................35 Browser-based Developer Tools ...............................................................................36 Debugging for UI Responsiveness ...........................................................................48 Minification ...........................................................................................................................59 Code-quality Tools ...........................................................................................................61 Conclusion .......................................................................................................................... 66 Chapter 3: Custom Properties ........................................................67 Table of Contents iii
Defining a Custom Property........................................................................................ 68 Using Custom Properties ............................................................................................. 69 Custom Properties and the Cascade ...................................................................... 71 Using Custom Properties with JavaScript.............................................................72 Custom Properties and Components......................................................................73 Using Custom Properties and Media Queries .....................................................76 Conclusion ...........................................................................................................................77 Chapter 4: Working with Text..........................................................78 Better-looking Text with @font-face ........................................................................79 Variable Fonts .....................................................................................................................84 Strategies for Font Optimization............................................................................... 88 Writing Modes ....................................................................................................................92 Conclusion ........................................................................................................................ 106 Chapter 5: Layouts....................................................................................107 Display Types and Normal Flow ............................................................................. 108 Floating Elements and Normal Flow..................................................................... 117 Positioning and Stacking Elements........................................................................123 Using CSS Multicolumn Layout ...............................................................................134 Creating Layouts with CSS Grid ...............................................................................157 Creating Flexible Layouts with Flexbox ...............................................................191 Box Alignment and Distribution ..............................................................................200 iv CSS Master
Choosing flex or grid ................................................................................................... 211 Conclusion ......................................................................................................................... 211 Chapter 6: Transitions and Animations...............................213 CSS Transitions.................................................................................................................214 CSS Animation ..................................................................................................................231 A Note About Accessibility........................................................................................239 A Note About Performance.......................................................................................239 Conclusion .........................................................................................................................241 Chapter 7: Transforms.......................................................................... 242 How Transforms Affect Layout ................................................................................ 245 2D Transform Functions.............................................................................................. 253 Current Transform Matrix ...........................................................................................260 Matrix Multiplication and the Matrix Functions ...............................................262 3D Transform Functions..............................................................................................267 Creating Depth with the perspective Property ................................................280 Modifying the Point of View with perspective-origin..................................282 Preserving Three Dimensions with transform-style ....................................285 Showing Both Faces with the backface-visibility Property ...................288 Conclusion ........................................................................................................................295 Chapter 8: Applying CSS Conditionally ............................296 Table of Contents v
Media Queries and @media.......................................................................................... 297 Testing for Property Support with @supports .....................................................315 Conclusion ........................................................................................................................ 318 Chapter 9: Using CSS with SVG...................................................319 Vector Images versus Raster Images...................................................................320 Associating CSS with SVG Documents.................................................................321 Differences between SVG and HTML................................................................... 325 Styling SVG Elements ..................................................................................................326 Animating and Transitioning SVG CSS Properties..........................................329 Using SVG with Media Queries.................................................................................331 Conclusion ........................................................................................................................338 Chapter 10: Conclusion ...................................................................... 339 CSS Shapes.......................................................................................................................340 CSS Masking..................................................................................................................... 342 Scroll Snap ........................................................................................................................ 345 Blend Modes and CSS Filters................................................................................... 347 How to Follow Changes and Additions to CSS ................................................349 vi CSS Master
Preface CSS has grown from a language for formatting documents into a robust language for designing web applications. Its syntax is easy to learn, making CSS a great entry point for those new to programming. Indeed, it’s often the second language that developers learn, right behind HTML. However, the simplicity of CSS syntax is deceptive. It belies the complexity of the box model, stacking contexts, specificity, and the cascade. It’s tough to develop interfaces that work across a variety of screen sizes and with an assortment of input mechanisms. CSS mastery lies in understanding these concepts and how to mitigate them. Mastering CSS development also means learning how to work with new tools such as linters and optimizers. Linters inspect your code for potential trouble spots. Optimizers improve CSS quality, and reduce the number of bytes delivered to the browser. And of course, there’s the question of CSS architecture: which selectors to use, how to modularize files, and how to prevent selector creep. CSS has also grown in its capabilities. Until recently, we had to use clunky methods such as float, or weighty JavaScript libraries, to create the kinds of layouts that are now possible with the Flexbox, multicolumn, and Grid layout modules. Three-dimensional effects were impossible—or required images—before the rise of CSS transforms. Now we even have support for variables. What's Changed in This Edition? The second edition of a book may be tougher to write than a first edition. You have to determine what to keep, what to remove, and what to update. Much has changed in the three years since CSS Master was first published. Preprocessors and post-processors are less relevant today. Browser vendors have abandoned vendor prefixes. Variables can be replaced by custom properties. As a result, we won’t discuss them in this edition. CSS Grid layout, on the other hand, was considered leading edge in the last edition. It’s now widely supported and fully included in this one. This edition also includes introductions to writing modes, and box alignment—two CSS modules that interact with and affect Grid, multicolumn, and Flexbox layouts. Something else that’s changed: web users receive browser updates far more frequently, and there are more flavors of WebKit than before. Trying to keep up with each of these versions is a Preface vii
special kind of folly. So you’ll notice there are no browser support charts in this edition. It’s still a fascinating time to be a front-end developer. My hope is that you’ll come away from this book with a better sense of how CSS works and how to write it well. Who Should Read This Book? This book is for intermediate-level CSS developers, as it assumes a fair amount of experience with HTML and CSS. No time is spent covering the basics of CSS syntax. Coverage of CSS concepts such as the box model and positioning are included to illuminate tricky concepts for the experienced developer, but this coverage is not meant as an introduction for beginners. Experience with JavaScript is helpful, but not necessary. Conventions Used You’ll notice that we’ve used certain typographic and layout styles throughout this book to signify different types of information. Look out for the following items. Code Samples Code in this book is displayed using a fixed-width font, like so: <h1>A Perfect Summer's Day</h1> <p>It was a lovely day for a walk in the park. The birds were singing and the kids were all back at school.</p> Where existing code is required for context, rather than repeat all of it, ⋮ will be displayed: function animate() { ⋮ new_variable = "Hello"; } Some lines of code should be entered on one line, but we’ve had to wrap them because of page constraints. An ➥ indicates a line break that exists for formatting purposes only, and should be ignored: URL.open("http://www.sitepoint.com/responsive-web- ➥design-real-user-testing/?responsive1"); viii CSS Master
Tips, Notes, and Warnings Supplementary Materials https://github.com/spbooks/csspro2 is the book’s code archive, which contains code examples found in the book, plus game library that we’ll build in the book. https://www.sitepoint.com/community/ are SitePoint’s forums, for help on any tricky problems. books@sitepoint.com is our email address, should you need to contact us to report a problem, or for any other reason. Hey, You! Tips provide helpful little pointers. Ahem, Excuse Me ... Notes are useful asides that are related—but not critical—to the topic at hand. Think of them as extra tidbits of information. Make Sure You Always ... ... pay attention to these important points. Watch Out! Warnings highlight any gotchas that are likely to trip you up along the way. Preface ix
CSS Architecture and Organization Chapter 1 10 CSS Master
If you’ve ever worked on a CSS codebase of any size—or even a small codebase with multiple developers—you’ll have realized how difficult it is to create CSS that’s predictable, reusable, and maintainable without being bloated. With added developers often comes added complexity: longer selectors, colliding selectors, and larger CSS files. In this chapter, we’ll explore CSS architecture and organization. First up: file organization. We’ll take a look at strategies for managing CSS across projects, or as part of your own CSS framework. Then we’ll look at specificity. It’s a frequent pain point for CSS development, especially for teams. Specificity is the means by which browsers decide which declarations to apply. If you’ve ever wondered why all of the buttons on your site are green when you wanted some of them to be orange, this section is for you. We’ll discuss how to calculate selector specificity, and choose selectors that maximize reusability while minimizing the number of characters you’ll need. Finally, we’ll discuss some guidelines and methodologies for writing CSS. These rules make it easier to avoid selector-naming collisions and overly specific selectors—the kinds of issues that arise when working within teams. File Organization Part of a good CSS architecture is file organization. A monolithic file is fine for solo developers or very small projects. For large projects—sites with multiple layouts and content types, or multiple brands under the same design umbrella—it’s smarter to use a modular approach and split your CSS across multiple files. Splitting your CSS across files makes it easier to parcel tasks out to teams. One developer can work on typography-related styles, while another can focus on developing grid components. Teams can split work sensibly and increase overall productivity. So what might a good file structure that splits the CSS across files look like? Here’s a structure that’s similar to one that I’ve used in projects: typography.css : font faces, weights, line heights, sizes, and styles for headings and body text forms.css : styles for form controls and labels lists.css : list-specific styles tables.css : table-specific styles accordion.css : styles for the accordion component cards.css : styles for the card component CSS Architecture and Organization 11
CSS frameworks such as Foundation and Bootstrap use a similar approach. Both become quite granular, with separate files for progress bars, range inputs, close buttons, and tooltips. That granularity allows developers to include only the components they need for a project. The details of how you split your CSS will depend on your own preferences and practices. If your workflow includes a pre-processor such as Sass or Less, these would be partials with a .scss or .less extension. You may also add a _config.scss or _config.less file that contains color and font variables. Or perhaps you have a more component-centric workflow, as with the pattern-library tool Fractal, or JavaScript frameworks like React and Vue.js. You might instead opt for a single base.css or global.css file that smooths out browser differences, and use a separate CSS file for each pattern or component. 1-1. In many cases, you'll want to combine these smaller files into one larger bundle Something to avoid: organizing your CSS by page or view. Page-centric approaches encourage repetitious code and design inconsistencies; you probably don't need both .contact-page label and .home-page label rulesets. Instead, try to find common patterns or components in your site's design, and build your CSS around them. Using multiple files during site development doesn’t necessarily mean you’ll use multiple files in production. In most cases, you’ll want to optimize CSS delivery by concatenating files, and separating critical from non-critical CSS. We discuss optimization techniques in the chapter Debugging and Optimization. File organization is just one aspect of CSS architecture. Despite its position in this chapter, it’s actually the least important aspect. In my experience, most CSS architecture problems arise from selector choice and specificity. We’ll discuss how to avoid these issues in the next section. 12 CSS Master
Specificity A common observation, particularly from developers who are coming to CSS from more traditional programming languages, is this: CSS has a global scope. In other words, using button as a selector applies those declarations to every <button> element, whether that was intended or not. Where this begins to go awry is when we try to solve the “global” problem by using longer selectors—for example, changing button to form button or a to #content a . As your site or application adds more patterns and features, however, you may find yourself in a selectors arms race. You may add a form.location-search button selector to override form button or #content .sidebar a to override #content a . The “global” nature of CSS is really an issue of specificity and the cascade in Cascading Style Sheets. Although it may seem arbitrary at first, CSS has well-defined rules for determining what declarations to apply. Understanding specificity may be what separates good CSS developers from CSS masters. Think of specificity as a score or rank that determines which style declarations are applied to an element. The universal selector ( * ) has a low degree of specificity. ID selectors have a high degree. Descendant selectors such as p img and child selectors such as .panel > h2 are more specific than type selectors such as p , img , or h1 . Class names fall somewhere in the middle. Higher-specificity selectors are higher priority selectors. Declarations attached to high specificity selectors are the what the browser ultimately applies. Calculating exact specificity values seems tricky at first. As explained in the Selectors Level 3 specification, you need to: count the number of ID selectors in the selector (= A) count the number of class selectors, attribute selectors, and pseudo- classes in the selector (= B) count the number of type selectors and pseudo-elements in the selector (= C) ignore the universal selector If you're like me, you may have to stare at these rules for a while before they make sense. CSS Architecture and Organization 13
A, B, and C combine to form a final specificity value. ID selectors such as #foo have a specificity of 1,0,0—that's one ID selector, and no class or type selectors. Attribute selectors, such as [type=email] and class selectors such as .story have a specificity of 0,1,0. Adding a pseudo- class such as :first-child (for example, .story:first-child ) gives us a specificity of 0,2,0. But using a simple type or element selector such has h1 or p only gives us a specificity of 0,0,1. Pseudo-elements such as ::before and ::after are as specific as type selectors (0,0,1). When two selectors are equally specific, the cascade kicks in, and the last rule wins. Here’s an example: a:link { color: #369; } a.external { color: #f60; } Both a:link and a.external have a specificity value of 0,1,1—zero ID selectors, one class or pseudo-class, and one type (or element) selector. However, the a.external ruleset follows the a:link ruleset. As a result, a.external will take precedence. In this case, most of our links will be cadet blue. But those with class="external" will be orange. Complex and combinator selectors, of course, give us higher specificity values. Consider the following CSS: ul#story-list > .book-review { color: #0c0; } #story-list > .book-review { color: #f60; } Although these rulesets look similar, they aren’t the same. The first selector, ul#story-list > .bookreview , contains a type selector ( ul ), an ID selector, ( #story-list ), and a class selector ( .bookreview ). It has a specificity value of 1,1,1. The second selector, #story-list > .book-review only contains an ID and a class selector. Its specificity value is 1,1,0. Even though Learning More About Specificity Keegan Street’s Specificity Calculator and Joshua Peek’s CSS Explain are helpful for learning about and calculating selector specificity. 14 CSS Master
our #story-list > .book-review rule follows ul#story-list > .bookreview , the higher specificity of the former means that those elements with a .book-review class will be green rather than orange. Choose Low-specificity Selectors Err on the side of using low-specificity selectors. They make it easier to reuse your CSS, and they extend patterns in new ways. Consider the following: button[type=button] { background: #333; border: 3px solid #333; border-radius: 100px; color: white; line-height: 1; font-size: 2rem; padding: .5rem 1rem; } This gives us a charcoal gray button with white text, and rounded ends, as shown in the following image: CSS Architecture and Organization 15
1-2. A charcoal gray button with white text, styled using the CSS above Let’s add some styles for a close button. We’ll use a .close class, as shown below: button[type=button] { background: #333; border: 3px solid #333; border-radius: 100px; color: white; line-height: 1; font-size: 2rem; padding: .5rem; } .close { width: 3rem; height: 3rem; background: #c00; border: 0; border-bottom: 5px solid #c00; font-size: 3rem; 16 CSS Master
line-height: 0; padding: 0; } Now we have two charcoal gray buttons with white text and rounded ends: 1-3. Our second button inherits unintended styles from button[type=button] What’s happening? Our button[type=button] selector has a specificity of 0,1,1. However, .close is a class selector. Its specificity is only 0,1,0. As a result, most of our .close rules do not get applied to <button type="button" class="close"> . We can ensure that our .close styles are applied by either: changing .close to button[type=button].close making button[type=button] less specific CSS Architecture and Organization 17
The second option adds fewer bytes, so that’s what we’ll use: [type=button] { background: #333; border: 3px solid #333; border-radius: 100px; color: white; line-height: 1; font-size: 2rem; padding: .5rem; } .close { width: 3rem; height: 3rem; background: #c00; border: 0; border-bottom: 5px solid #c00; font-size: 3rem; line-height: 0; } Changing the specificity of our selector leaves us with our intended result: 18 CSS Master
1-4. Declarations attached to lower-specificity selectors are easier to override Avoid Chaining Class Selectors Another way to minimize specificity is to avoid chaining class selectors. Selectors such as .message.warning have a specificity of 0,2,0. Higher specificity means they’re hard to override. What’s more, chaining classes may cause side effects. Here’s an example: .message { background: #eee; border: 2px solid #333; border-radius: 1em; padding: 1em; } .message.error { background: #f30; color: #fff; } .error { CSS Architecture and Organization 19