1. Trang chủ
  2. » Ngoại Ngữ

CSS Mastery, 3rd Edition_ www.bit.ly/taiho123

428 5,8K 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 428
Dung lượng 21,55 MB

Nội dung

T HE E X P ER T ’S VOIC E ® IN W E B D E V E L O P M E N T CSS Mastery Advanced Web Standards Solutions — Third Edition — Andy Budd Emil Björklund www.it-ebooks.info CSS Mastery Advanced Web Standards Solutions Third Edition Andy Budd Emil Björklund www.it-ebooks.info CSS Mastery: Advanced Web Standards Solutions, Third Edition Andy Budd Brighton, United Kingdom Emil Björklund Malmo, Sweden ISBN-13 (pbk): 978-1-4302-5863-6 ISBN-13 (electronic): 978-1-4302-5864-3 DOI 10.1007/978-1-4302-5864-3 Library of Congress Control Number: 2016944612 Copyright © 2016 by Andy Budd and Emil Björklund This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director: Welmoed Spahr Acquisitions Editor: Ben Renow-Clarke Development Editor: Matthew Moodie Technical Reviewers: Anna Debenham and Andy Hume Editorial Board: Steve Anglin, Pramila Balen, Louise Corrigan, James DeWolf, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Nikhil Karkal, James Markham, Susan McDermott, Matthew Moodie, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing Coordinating Editor: Nancy Chen Copy Editor: Bill McManus Compositor: SPi Global Indexer: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springer.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ Printed on acid-free paper www.it-ebooks.info This book is dedicated to all my colleagues at Clearleft—both past and present Were it not for their support and wisdom, this book would never have happened —Andy Budd Dedicated to the memory of my grandfather: the engineer, artist, and life-long tinkerer Sven Forsberg (1919–2016) —Emil Björklund www.it-ebooks.info www.it-ebooks.info Contents at a Glance About the Authors xvii About the Technical Reviewers xix Acknowledgments xxi Introduction xxiii ■Chapter 1: Setting the Foundations ■Chapter 2: Getting Your Styles to Hit the Target 17 ■Chapter 3: Visual Formatting Model Overview 39 ■Chapter 4: Web Typography 61 ■Chapter 5: Beautiful Boxes 101 ■Chapter 6: Content Layout 143 ■Chapter 7: Page Layout and Grids 185 ■Chapter 8: Responsive Web Design & CSS 223 ■Chapter 9: Styling Forms and Data Tables 263 ■Chapter 10: Making It Move: Transforms, Transitions, and Animations 299 ■Chapter 11: Cutting-edge Visual Effects 335 ■Chapter 12: Code Quality and Workflow 371 Index 403 v www.it-ebooks.info www.it-ebooks.info Contents About the Authors xvii About the Technical Reviewers xix Acknowledgments xxi Introduction xxiii ■Chapter 1: Setting the Foundations Structuring your Code Maintainability A Brief History of Markup Progressive Enhancement Creating Structurally and Semantically Rich HTML Class and ID Attributes Structural Elements 10 Using Divs and Spans 11 Presentational Text Elements, Redefined 12 Extending the Semantics of HTML 12 Validation 15 Summary 15 ■Chapter 2: Getting Your Styles to Hit the Target 17 CSS Selectors 17 Child and Sibling Selectors 18 The Universal Selector 20 Attribute Selectors 21 Pseudo-Elements 22 vii www.it-ebooks.info ■ CONTENTS Pseudo-Classes 24 Structural Pseudo-Classes 25 Form Pseudo-Classes 27 The Cascade 29 Specificity 29 Order of Rules when Resolving the Cascade 30 Managing Specificity 31 Specificity and Debugging 33 Inheritance 34 Applying Styles to your Document 35 The Link and Style Elements 35 Performance 36 Summary 38 ■Chapter 3: Visual Formatting Model Overview 39 Box Model Recap 39 Box-Sizing 40 Minimum and Maximum Values 44 The Visual Formatting Model 44 Anonymous Boxes 46 Margin Collapsing 46 Containing Blocks 48 Relative Positioning 49 Absolute Positioning 49 Fixed Positioning 50 Floating 51 Formatting Contexts 56 Intrinsic and Extrinsic Sizing 58 Other CSS Layout Modules 58 Flexible Box Layout 58 Grid Layout 59 viii www.it-ebooks.info ■ CONTENTS Multi-Column Layout 59 Regions 59 Summary 59 ■Chapter 4: Web Typography 61 Basic Typesetting in CSS 61 Text Color 63 Font-Family 64 Font Size and Line Height 65 Line Spacing, Alignment, and the Anatomy of Line Boxes 68 Font Weights 70 Font Style 71 Transforming Case and Small-Cap Variants 71 Changing the Space Between Letters and Words 72 Measure, rhythm, and rag 73 Text Indent and Alignment 74 Hyphenation 76 Setting Text in Multiple Columns 77 Web Fonts 81 Licensing 82 The @font-face rule 83 Web Fonts, Browsers, and Performance 87 Loading Fonts with JavaScript 89 Advanced Typesetting Features 91 Numerals 93 Kerning Options and Text Rendering 94 Text Effects 95 Using and Abusing Text Shadows 95 Using JavaScript to Enhance Typography 98 Further Type Inspiration 99 Summary 99 ix www.it-ebooks.info CHAPTER 12 ■ CODE QUALITY AND WORKFLOW (http://stylelint.io/) These tools check both for syntax errors and patterns in your selectors and declarations that may be undesirable (see Figure 12-14) Both are configurable and you can even write your own rules Figure 12-14 Using CSS Lint in the Sublime Text editor Dots in the left gutter indicate potential problems, and the explanation message is printed on the bottom bar Build Tools Apart from linting, there are a lot of tasks outside of the editor that we may need to over and over again while developing a site: • Preprocessing CSS • Concatenating CSS files together, if working in multiple shorter files • Minifying CSS, removing comments and so forth to save space • Optimizing images referenced in the CSS • Running a development server • Reloading one or more browsers to inspect our changes Luckily, there are numerous tools that help you these tasks automatically in a project They range from more advanced tools run from the command line, to more simple setups that you can manage in a graphical user interface, like Koala (see Figure 12-15) 395 www.it-ebooks.info CHAPTER 12 ■ CODE QUALITY AND WORKFLOW Figure 12-15 Koala is a build tool GUI available for Windows, Mac, and Linux There are also lots of apps available that allow you to configure your build system entirely in code This typically requires a bit more setup, but since the configuration can then be shared among developers and projects, it can help keep development environments consistent and quick to set up Setting up a CSS Build Workflow with Node and Gulp Node is a flavor of JavaScript that you can run outside of a browser and use for any type of programming task Since Node came about, a lot of the tooling for front-end development is based on JavaScript, as people who already knew it could scratch their own itch, so to speak For front-end build workflows, there are lots of Node applications like Grunt, Gulp, and Broccoli (yes, those are the actual names) that specialize in managing build tasks They help by configuring and chaining together the output from separate tasks, each responsible for one part of the workflow For our example workflow, we are going to use Gulp, which is in turn handled via NPM, a utility program that comes with Node NPM is a command-line tool, so all of the commands in the example are run inside a terminal window ■ Note If you need a crash course in how to use the command line, go to http://learnpythonthehardway org/book/appendix-a-cli/introduction.html and work through some examples It can be a daunting task, but you will learn invaluable skills for managing your computer and taking advantage of more advanced tools 396 www.it-ebooks.info CHAPTER 12 ■ CODE QUALITY AND WORKFLOW First things first: you’ll need to install Node Go to https://nodejs.org to download and run the installer for your platform Next, navigate to the workflow-project folder inside the Chapter 12 examples in the code accompanying the book This folder has a file called package.json, which is the file that keeps track of what’s needed to run the project These dependencies are stored in a central code repository on https://www.npmjs.com, where hundreds of thousands of free code libraries are shared Normally, you’d create your own package file by invoking the command npm init and answer a few questions about your project, but this time we’ve gone down the TV-chef route and prepared one ahead of time To install the dependencies listed in the package file, run the command npm install This will download and install the following small applications, locally in your project folder: • Gulp: The task runner that puts the rest of the programs together • Gulp-sass: A version of the Sass preprocessor library • Browser-sync: A tool to run a lightweight development server, and synchronize the reloading of and interacting with web pages across browsers Also includes a debugger, so you can debug for example on mobile devices • Autoprefixer: An immensely useful library that inspects your CSS and adds the relevant prefixes and alternate syntaxes for CSS properties, based on a list of browsers that you want to support • Gulp-postcss: A version of the PostCSS preprocessor, which is needed to run Autoprefixer These applications will put their files in a folder called node_modules inside the project directory If you use any kind of version control for your files, you will probably want to tell it to ignore this folder: there will be thousands of tiny files inside, and you can re-create them at any time using the package file The next ingredient is the file gulpfile.js, which contains instructions for how to use the installed packages together We won’t go into all the details of how this works, but as an example, here’s the part that handles the preprocessing of CSS: gulp.task('styles', function(){ var processors = [autoprefixer()]; gulp.src(['*.scss']) pipe(sass()) pipe(postcss(processors)) pipe(gulp.dest('./')) pipe(browserSync.reload({stream:true})) }); When the gulp program is told to run the styles task, any scss file in the same directory is picked up It is then run through the Sass preprocessor After that, it runs through the PostCSS processor, where Autoprefixer appends the necessary prefixes It does so by going to http://caniuse.com and figuring out which prefixes and syntax changes to use By default it covers the latest two versions of all major browsers, plus browsers with an approximate market share of over 1%, but this setting is highly configurable Finally, the CSS is saved to disk and the browser-sync program is signaled to reload any connected browser windows 397 www.it-ebooks.info CHAPTER 12 ■ CODE QUALITY AND WORKFLOW To run tasks, we use NPM The package.json file contains a mapping of commands that target the applications that we installed When we now run npm run gulp, the default set of tasks is run, and continues to rerun automatically whenever we save a file, until we stop it The default browser on our machine also launches in a new tab, where the index.html file in the current directory is served As soon as the CSS file changes, the browser (and any other browser you point at the same address) reloads It’s easy to get lost when setting up task runners and workflows The win comes when you have it on file, and it’s ready to reuse across projects or share A new collaborator would only need to install Node and run npm install before they had the exact same setup on their machine Although wrestling with development tools is probably the least fun part of building websites for most people, it is often a type of “set it and forget it” task that can save lots of time in the long perspective, once you are up and running If you need a slightly more detailed introduction (using the Grunt task runner rather than Gulp), we recommend Chris Coyier’s article “Grunt for People Who Think Things Like Grunt are Weird and Hard” (https://24ways.org/2013/ grunt-is-not-weird-and-hard/) The Future of CSS Syntax and Structure Throughout this book, we have been using CSS features with various levels of browser support We have repeated the mantra of progressive enhancement in applying new features—meaning you can use a lot of them today, as long as you have a sensible alternative lined up when they aren’t yet supported This works for a lot of things, but not all There are some fundamental proposed changes to how we write CSS on the horizon Some of these are experimentally supported already, but as they are hard to apply in a progressive way, it’s likely that it will be a few years before we’ll be able to use all of them in our day-to-day workflows Nevertheless, it is useful to keep an eye out for where CSS is headed Custom Properties—Variables in CSS The addition of variables to CSS has been one of the most-requested features for a long time A spec has been in the works for several years, and only recently became a Candidate Recommendation As this book is being written, Chrome and Safari are on the verge of releasing versions with support Firefox has already supported variables for quite a while The technically correct name for these variables is custom properties: they look an awful lot like how variables work in, for example, Sass, but are slightly different A custom property is declared using syntax much like a vendor-prefixed property, except the vendor name is empty, resulting in two initial dashes To define a variable that is to be available globally, you can add it to the :root selector You can also define (or redefine) a variable to have a specific value in a specific selector context :root { my-color: red; } myThing { my-color: blue; } 398 www.it-ebooks.info CHAPTER 12 ■ CODE QUALITY AND WORKFLOW We can access the value of a custom property anywhere that the value has cascaded The var() functional notation pulls the custom property value out, with the option of a fallback value if the property is undefined or invalid In the following snippet, the color declaration will be set to blue, since the previous example set it on the myThing ancestor: myThing myInnerThing { /* second (optional) argument is the fallback */ color: var( my-color, purple); } Custom properties can be used with var() not just as the entire value, but as part of another subvalue: :root { max-columns: 3; } myThing { columns: var( max-columns, 2) 12em; } Since preprocessors like Sass have variables built in, why would we choose to this work on the client rather than beforehand via a build script or server process? Well, since custom properties are calculated in the browser and not beforehand, they have access to the live DOM tree and the whole cascade If something changes, the styles can be recalculated If we use JavaScript to set the my-color variable for the html element after the page has loaded, every element that depends on that color value updates its color instantly It’s tricky to start using custom properties for any significant parts of your code before a wide range of browsers supports them Any fallbacks to regular values would necessarily result in a lot of duplicated declarations Nevertheless, they are no doubt a powerful addition to CSS HTTP/2 and Server Push A lot of the performance-related patterns we use today are related to how HTTP works More specifically, we try to counter the fact that the current version, HTTP/1.1, is relatively slow when it comes to fetching multiple things at once, so we mash together all of our styles into one file, and avoid external requests like the plague In HTTP/2, the underlying protocol is optimized for delivering many small assets at once A single connection can carry multiple files, reducing a lot of the overhead for making new requests There’s also some smart thinking in HTTP/2 with regard to how web pages are delivered Using something called “Server Push,” the server can automatically deliver a single response containing both HTML and CSS, unless the request signals that the browser already has the CSS file in its cache These new advances may help us get rid of patterns like inlining styles, or making image sprites The @import statement, which has been an anti-pattern of sorts for a long time, can get a new lease on life, allowing us to split up files as we like, without worrying about the extra request overhead HTTP/2 is supported in a lot of places already, and can be used today, as it falls back to the old behavior when unsupported in a browser It does require that the web server you are using supports it, however As with many infrastructure changes, this means that it will take some time before it’s truly mainstream and built into our tools 399 www.it-ebooks.info CHAPTER 12 ■ CODE QUALITY AND WORKFLOW Web Components Web Components is a name for a range of standards that allow web developers to package up HTML, CSS, and JavaScript into truly self-contained and easily reusable components, almost as if they were native elements When using a Web Component, you should be able to drop it right into your project, without worrying about naming collisions between your styles (or scripts) and those belonging to the component If we had created a hypothetical Web Component for including thumbnail previews from the Internet Movie Database (http://www.imdb.com), we would use a JavaScript file to tell the browser that we intended to use a custom imdb-preview element in our markup This element could then be invoked like this in HTML:

Ngày đăng: 22/11/2016, 11:54

TỪ KHÓA LIÊN QUAN