Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[译] [043] 关于本书 #15

Closed
cssmagic opened this issue Oct 14, 2015 · 2 comments
Closed

[译] [043] 关于本书 #15

cssmagic opened this issue Oct 14, 2015 · 2 comments

Comments

@cssmagic
Copy link
Owner


本文是早期译版,未经校审。仅供参考。


About this book

关于本书

Who this book is for

这本书适合谁

The primary target audience for this book is intermediate to advanced CSS developers. By getting the introductory stuff out of the way, we can explore more advanced use cases of modern CSS features and combinations thereof. This, however, means that quite a few assumptions have been made about you, dear reader:

这本书的主要目标受众是正在由中级向高级进阶的 CSS 开发者。我们将跳过基础入门部分,直接探索现代 CSS 特性所针对的更高级的应用场景,并将它们融汇贯通。不过在此之前,亲爱的读者朋友,我假设你已经具备以下条件:

  • I assume you know CSS 2.1 inside out, and have a few years of experience with it. You don’t struggle to understand how positioning works. You’ve used generated content to enhance your designs without extraneous markup or images. You don’t resort to plastering !important all over your code because you actually understand specificity, inheritance, and the cascade. You know what the different parts of the box model are, and you are not fazed by margin collapsing. You are familiar with the different length units and know when it’s best to use each one.
  • 我假设你已经彻底掌握了 CSS 2.1,并有数年的实践经验。你不需要费劲地猜测定位的原理是什么。你在增强网页设计效果时,会使用生成性内容,而不是依赖冗余的标签和图片。你不会在代码中到处使用 !important 来打补丁,因为你已经深入理解选择符优先级、继承和层叠机制。你知道盒模型中的各个部分都是什么,而且不会为外边距重叠头疼不已。你对各种长度单位了如指掌,而且清楚它们分别该用在什么地方。
  • You’ve read quite a bit about the most popular CSS3 features, online and/or in books, and have tried them out, even if only in personal projects. Even if you haven’t studied them in depth, you know how to create rounded corners, add a box-shadow, or create a linear gradient. You’ve played with some basic 2D transforms, and have enhanced interactions with basic transitions and animations.
  • 你已经在书里或在网上了解过最流行的 CSS3 特性都有哪些,并且已经亲手尝试过——哪怕只是用在自己的小项目里。即使你还没有深入地研究过它们,但你已经知道如何生成圆角、加上投影、或生成一个线性渐变图案。你玩过基本的 2D 变形(transform),并通过简单的过渡(transition)和动画(animation)来增强交互体验。
  • You have seen SVG and know what it’s used for, even if you don’t quite know how to write it yourself.
  • 你知道 SVG,并且知道它是做什么的,即使你还不那么清楚自己该怎么写一个出来。
  • You can read and understand basic, vanilla JavaScript, such as creating elements, manipulating their attributes, and adding them to the document.
  • 你可以读懂简单的、原生的 JavaScript 代码,比如创建元素、操作它们的属性、把它们添加进文档等等。
  • You’ve heard of CSS preprocessors and know what they can do, even if you choose not to use one.
  • 你听说过 CSS 预处理器,并且知道它们可以做什么,哪怕你决定一个也不用。
  • You’re familiar with middle school level math, such as square roots, the Pythagorean theorem, sines, cosines, and logarithms.
  • 高一数学应该难不倒你,比如平方根、勾股定理、三角函数、对数等等。

However, to enable readers that don’t meet all these assumptions to enjoy this book, there is a “Prerequisites” box in the beginning of some secrets, briefly listing any CSS knowledge or previous secrets that need to be known for the secret to make sense (excluding CSS 2.1 features, otherwise the box would get really long). It looks like this:

尽管如此,为了让不完全符合上述条件的读者也可以愉快阅读这本书,在每篇攻略的开头,我都会准备一个 “背景知识” 提示框,简要地列出读懂当前攻略所必需的 CSS 知识以及前面相关的攻略(不过 CSS 2.1 的内容就不列出了,否则这个提示框会撑爆的)。这个提示框是这个样子的:

Prerequisites

  • box-shadow
  • basic CSS gradients
  • the “Flexible ellipses” secret on page 76

背景知识

  • box-shadow
  • 基本的 CSS 渐变
  • “{$secret$}” 攻略(第 {$page$} 页)

This way, even if certain things are not already known, one can read up about them and come back to the secret afterward. As long as their prerequisites are met, the secrets can actually be read in any order, though there is value in reading them in the book order, as a lot of thought has been put into what the optimal order is.

这样一来,哪怕你暂时还没有掌握这些基础知识,也可以在补好课之后再回来阅读。只要你具备了某篇攻略所要求的背景知识,就可以直接学习它了,不用在乎顺序。不过,还是建议你按照书中的顺序来阅读,因为我花了很多心思才把这些章节调整到最佳顺序。

Note that I mentioned “CSS developers” and that “design skills” are not in the list of assumptions above. It’s important to note that this is not a design book. While it unavoidably touches on certain design principles and describes a few UX improvements, CSS Secrets is first and foremost a book about solving problems with code. CSS might have a visual output, but it is still code, just like SVG, WebGL/OpenGL, or the JavaScript Canvas API is code, not design. Writing good, flexible CSS requires the same kind of analytical thinking that programming does. Nowadays, most people use preprocessors for their CSS, with variables, math, conditionals, and loops, so it’s almost starting to look like programming!

请注意,我在上面列出的条件中说的是 “CSS 开发者”,并没有要求任何 “设计能力”。一定要意识到这并不是一本关于设计的书。虽然我们会不可避免地涉及一定的设计原理、阐述一些用户体验的改进方式,但这本书的初衷和核心价值是帮助你用代码解决问题。CSS 会产生视觉上输出结果,但它仍然还是代码,就好比 SVG、WebGL/OpenGL 或 JavaScript 里的 Canvas API,它们都是代码,而不是设计。编程要求我们具备条理性的思维,而想要写出合理的、灵活的 CSS 代码同样如此。如今,绝大多数 CSS 开发者都在使用 CSS 预处理器,他们会用到变量、数学计算、条件判断和循环,因此写 CSS 看起来已经像是在编程了。

This is not to imply that designers are discouraged from reading this book. Anybody who has sufficient coding experience with CSS can benefit from it, and there are many talented designers who can also write excellent CSS code. However, it’s important to note that teaching you how to improve the visual design or usability of a website is not among the goals of this book, even if it happens as a side effect.

当然这并不是说不鼓励设计师们读这本书。任何人只要具备足够的 CSS 编写经验,都可以从本书中受益;而且有很多才华横溢的设计师可以写出非常出色的 CSS 代码。总之,希望大家可以明白,这本书的目标并不是教大家如何改进网站的视觉设计或可用性——即使它在这些方面会起到间接的帮助。

Format & conventions used

本书采用的格式和约定

The book consists of 47 “secrets,” grouped by topic in seven chapters. These secrets are more or less independent and—as long as their prerequisites are met—can be read in any order. The demos in every secret are not complete websites, or even parts thereof. They are purposefully as small and simple as possible, in order to facilitate understanding. The assumption is that you already know what you want to implement. The purpose of this book is not to give design ideas, but implementation solutions.

这本书包含了 47 篇攻略,并根据主题的不同收入到 7 章中。这些攻略基本上是相互独立的,并且可以以任意顺序阅读——只要你掌握了各篇攻略所需的背景知识。在每篇攻略中出现的演示案例并不是完整的网站,甚至连网站的片断都算不上。这些案例有意设计得尽量简短,以便降低理解负担。这本书的目的并不是要给出设计创意,而是给出创意的实现方案。

Every secret is split into two or more sections. The first section, titled “The problem,” introduces a common CSS challenge that we are going to solve. Sometimes this introduction might describe widely popular solutions that are suboptimal (e.g., solutions that require a lot of markup, hardcoded values, etc.), and usually concludes with variations of the question “Is there a better way to achieve this?”

每篇攻略分为两个或多个大段。第一大段叫作 “难题”,会引入一项常见的 CSS 挑战,需要我们去解决。有时这个引言可能会列出一些广泛流行但不够完美的解决方案(比如,需要添加大量的结构标记、需要死写数值等等),而且往往会以类似 “还有更好的方法吗” 这样的设问作为结尾。

After introducing the problem, one or more solutions follow. This book was inspired by the CSS talks I have presented at various conferences so I tried to maintain the interactive presentation format as much as a book allows. Therefore, every solution is illustrated by a number of figures, demonstrating the visual output for every step of the solution that results in a visual change. Because figures are not always directly next to the text that describes what they demonstrate, they are numbered and referenced in the text. You can see an example of a figure in Figure P.1 and the current sentence was an example of a reference to it.

在引入问题之后,会给出一个或多个解决方案。这本书的灵感来源于我在各种技术会议上所作的 CSS 演讲,因此我尝试在书中尽可能保持那种互动式的风格。因此,每种解决方案都会配以多幅插图,把每个会产生视觉变化的步骤都用图片演示出来。由于所有插图不一定都能紧贴着对应的段落,我就给它们都编上号,这样就可以在正文中引用这些插图。你可以在 图 P.1 中看到一个插图的示例,而且这句话本身也是一个引用插图的示例。

图 P.1

FIGURE P.1

This is an example sidebar figure, introducing the great Sir Adam Catlace

这是一个侧栏插图的示例。图中是伟大的 Adam Catlace 爵士。


{原书注释!}

Notes, such as this one, provide additional information or explain a term mentioned in the text.

这里是侧栏注解。它会提供额外信息,或解释正文中提到的某个术语。


{警告!!}

[!] This is a warning. Its purpose is to warn you (surprising, I know!) about possible false assumptions and certain things that could go wrong.

这是一个警告。它的作用是警告你(要做好心理准备哦),为你指出一些常见的误区,或提醒你哪些地方容易出错。

Inline code is denoted by monospace text and colors often have a small preview next to them as well (e.g., #f06). Block-level code looks like this:

行内的代码采用 等宽字体 来表示,颜色值也是如此。颜色值前面通常还会加一个小的预览色块(比如这样 #f06)。而代码块则是这样的:

background: url("adamcatlace.jpg");

or this:

或这样的:

<figure>
    <img src="adamcatlace.jpg" /> 
    <figcaption>Sir Adam Catlace</figcaption>
</figure>

As you might have noticed, when the language of a code block is not CSS, it’s noted in the top-right corner. Also, when the example discussed only involves a single element, and no pseudo-classes or pseudo-elements are involved, there is usually no selector or braces ({}) included in the code blocks, for brevity.

你可能已经看出来了,只有当代码块的语言不是 CSS 时,语言类型才会在右上角标记出来。同样,为简洁起见,当示例代码只涉及单个元素、不涉及伪类或伪元素时,通常就不再把选择符和花括号({})写出来了。

All JavaScript examples in the book are vanilla JavaScript, with no frameworks or libraries required. There is only one helper function used, $$(), in order to make it easier to loop over a set of elements that match a certain CSS selector. The function’s definition is:

本书中的所有 JavaScript 示例都是原生的 JavaScript,不需要依赖任何类库或框架。我们只会用到一个工具函数——$$(),它可以让我们更容易地获取和遍历所有匹配特定 CSS 选择符的 DOM 元素。这个函数的定义如下:

function $$(selector, context) {
    context = context || document;
    var elements = context.querySelectorAll(selector);
    return Array.prototype.slice.call(elements);
}

{小花絮}

[TRIVIA] Side trivia

随便聊两句

Dark “Trivia” sections at the bottom of pages introduce tangentially related trivia, such as the historical or technical background behind a CSS feature. They are not necessary for using or understanding the main material, but readers might find them interesting nevertheless.

书页最底部深色调的 “小花絮” 段落会扯得稍微远一些,比如介绍一下某个 CSS 特性背后的历史性的或技术性的趣闻。它们对使用和理解正文内容没有直接作用,但读者或许会在这里发现他们感兴趣的东西。

Every secret includes one or more live examples that can be accessed with short, memorable URLs in play.csssecrets.io. The references to them look like this:

每篇攻略至少会附上一个在线示例,URL 都在 play.csssecrets.io 域名下,而且都很简短易记。这些在线示例的链接是这样展示的:

{试一试} play.csssecrets.io/polka

It is strongly recommended that you check out the “Play!” examples, especially if you are confused by the techniques described or if you get stuck while following along.

强烈建议你打开这些 “试一试” 示例,尤其是当你对文中所述的技巧不那么清楚时,或者当你在读到某个地方卡住了的时候。

{致敬}

Credit where it’s due: When a technique described was first documented by someone else in the community, credit will be given in a “Hat Tip” paragraph like this one, referencing the URL of the source as well. We all know that having to find the “References” section at the end of a book is a hassle, so these essentially provide references in context.

该表扬就表扬:当文中提到的某个技巧是某人在社区中首次提出时,我们都会在类似本段这样的 “致敬” 环节向他发出谢意,同时也会给出相关链接。如果把这些链接都放在全书末尾的 “参考链接” 章节,查起来会很不方便,因此我们将采用就近注解的方式。


{关于未来}

[FUTURE] Future solutions

未来的解决方案

“Future” sections (positioned at the bottom of pages and set on a dark background) introduce techniques that are already in draft specifications, but at the time of writing have no implementations. Readers should always check if these techniques are supported, as they might have been implemented after the publication of this book. In cases where the feature is obscure enough that browser support websites might not include it, the section will include a test that the reader can load, in short memorable URLs, such as the one shown here in the “Test!” example. These tests are usually designed so that shades of green appear when the feature is supported and shades of red otherwise. The exact instructions are mentioned in the code, as a comment.

“关于未来” 段落(通常安排在书页的最底部、并配以深色背景)会介绍一些已经被列入规范草案的技术,但在编写本书时可能还没有浏览器实现。但你在阅读本书的时候,别忘了再次查证这些特性是否已经可用了,因为当本书出版后,浏览器可能已经实现了。考虑到这些特性的草案可能还很不稳定,浏览器兼容性查询网站可能还没有包含它们,因此,这个段落同样也会提供一个测试性的示例页面,以便读者自行查验。这些测试页面的 URL 同样也很简短易记,会以下面这样 “测一测” 的形式标注出来。这些测试通常是这样设计的——绿色阴影表示当前浏览器已经支持某个特性,而红色阴影反之。在测试代码的注释中,也提供了明确的说明。


{测一测} play.csssecrets.io/test-conic-gradient

At the end of almost every secret you’ll find a list of related specifications that looks like this:

在每篇攻略的末尾,你还会发现一份相关规范的清单,就像下面这样:

[RELATED SPECS]

相关规范

This includes references to all the specifications from which features were mentioned. However, just like the “Prerequisites” box, this does not apply to CSS 2.1, otherwise it would be listed in the “Related Specs” section of every single secret. This means that the few secrets that only discuss CSS 2.1 features have no “Related Specs” section at all.

这份清单列出了当前攻略所述技术所对应的各项技术规范。不过,跟前面提到的 “背景知识” 提示框一样,这份清单也不再列出 CSS 2.1 的内容。这意味着,少数几篇只讨论 CSS 2.1 的攻略就根本没有 “相关规范” 这个段落了。

Browser support & fallbacks

浏览器支持与回退机制(Fallback)

Possibly the biggest peculiarity of this book is the complete lack of browser compatibility tables. This was a conscious decision, as with today’s browser release cycles, such information is bound to get out of date before this book even hits the shelves. I believe that inaccurate browser support information is misleading, and is actually worse than no information.

本书的最大创举可能就是完全不提供浏览器兼容性表格。这是一个经过深思熟虑的决定,因为以当前浏览器的更新频繁来看,这些信息必定在书还没有上架时就已经过时了。我认为不准确的浏览器支持信息极具误导性,还不如干脆没有。

However, most secrets described either currently have decent browser support and/or degrade gracefully. In cases where a technique described presently has particularly poor browser support, there is a “Limited Support” warning icon next to the relevant solution, like the one next to this paragraph. This should be enough to hint that you should not use the solution without looking up browser support for it and taking extra care for providing good fallbacks.

尽管如此,书中大多数攻略要么已经在浏览器中获得了良好支持,要么可以做到平稳退化。万一某项技术在眼下的支持程度特别不理想时,我会在紧邻相关段落的侧栏处设置一个 “不完全支持” 的警告图标,比如本段旁边就有一个示例。它应该足以提醒你在正式使用这些技术之前不要忘了查证一下浏览器的支持情况,并且要特别注意做好回退机制。

{警告!!} 不完全支持

[LIMITED SUPPORT]

There are plenty of excellent websites containing up-to-date browser support information. Here are some suggestions:

有很多优秀的网站提供了及时有效的浏览器兼容性信息。推荐如下:

Sometimes you might find that a certain feature is supported, but slightly differently across browsers. For example, it might need a vendor prefix, or slightly different syntax. Only the standards-compliant, unprefixed syntax will be included in the examples. However, you can almost always use different syntaxes alongside and let the cascade take care of which one wins. For this reason, always place the standard version last. For example, to get a vertical linear gradient from yellow to red, the book would only list the standard version:

有时候你可能会发现某个特性已经被浏览器支持了,但不同浏览器的表现可能还有着细微的差异。比如说,它可能需要一个浏览器前缀,或者在语法上存在细微的差别。我们的示例代码中只会包含符合标准的、无前缀的语法。不过在绝大多数情况下,你都可以同时使用各种不同的语法,并且通过层叠机制来确保哪条声明最终生效。出于这个原因,你应该把标准语法排在最后。举例来说,要得到一条从黄色到红色的垂直渐变色,本书只会列出标准语法:

background: linear-gradient(90deg, yellow, red);

However, if you want to support very old browsers, you might end up having to write something like the following:

但是如果你想要支持那些较早些的浏览器,你可能得把代码写成这样才能奏效:

background: -moz-linear-gradient(0deg, yellow, red);
background: -o-linear-gradient(0deg, yellow, red);
background: -webkit-linear-gradient(0deg, yellow, red);
background: linear-gradient(90deg, yellow, red);

{原书注释!}

You can read more on vendor prefixes, why they exist, and how to abstract them away from your code in the “A story of ice, fire, and vendor prefixes” section on page {$page$}.

关于浏览器前缀的更多信息,比如它们为什么会存在,以及如何在代码中把它们抽象出来,你可以在 **“{$section$}” 段落(第 {$page$} 页)**中进一步了解。

Because the landscape of these differences is just as fluid as browser support, it is expected that things like this are part of your standard research before using a CSS feature and are not discussed further in the solutions presented.

这种差异的局面跟浏览器兼容性的局面一样,时刻处在变化之中,因此,当你在使用某项 CSS 特性之前,不要忘记这方面也是你要做好的功课,而且本书就不再为此花费过多篇幅了。

Similarly, most of the time it’s good practice to provide fallbacks, so that your website doesn’t break in older browsers, even if it doesn’t look as fancy in them. These are not discussed extensively when they are obvious, as the assumption is that you know how the cascade works. For example, when specifying a gradient, such as the one just shown, you should also add a solid color version before all of them. A good idea for the solid color might be the average of the two gradient colors (in this case, rgb(255, 128, 0)):

还有一些内容我们也不再赘述了。提供回退机制通常是一种很好的做法,这样可以确保你的网站不会在低版本浏览器中挂掉,只是看起来没有那么炫而已。当这些后备机制很明显的时候,我们就不展开讨论了,因为你应该已经很清楚样式声明的层叠机制了。举例来说,当我们像上面那样指定一个渐变色作为背景的时候,你应该在前面添加一行实色背景的声明。如果这个实色是取自渐变色的平均色值(比如在这个例子中是 rgb(255, 128, 0)),那便是极好的。

background: rgb(255, 128, 0);
background: -moz-linear-gradient(0deg, yellow, red);
background: -o-linear-gradient(0deg, yellow, red);
background: -webkit-linear-gradient(0deg, yellow, red);
background: linear-gradient(90deg, yellow, red);

However, sometimes it’s not possible to provide decent fallbacks through the cascade. As a last resort, you could use tools like Modernizr, which adds classes like textshadow or no-textshadow to the root element (<html>), so you can use them to target elements only when certain features are (not) supported, like so:

不过,有些时候不太可能只通过样式的层叠就可以提供完善的回退样式。这时别忘了你还有一招,可以使用 Modernizr 这样的工具来给根元素(<html>)添加一些辅助类,比如 textshadowno-textshadow 等等,这样你就可以针对支持或不支持某些特性的浏览器来分别编写样式了,就像这样:

h1 { color: gray; }

.textshadow h1 {
    color: transparent;
    text-shadow: 0 0 .3em gray;
}

If the feature you are trying to create a fallback for is sufficiently new, you could use the @supports rule, which is the “native” Modernizr. For example, the preceding code would become:

如果你想尝试使用的某个 CSS 特性非常新,还可以试试用 @supports 规则来实现回退,它可以视作浏览器 “原生的” Modernizr。比如说,上面的代码还可以这样写:

h1 { color: gray; }

@supports (text-shadow: 0 0 .3em gray) { 
    h1 {
        color: transparent;
        text-shadow: 0 0 .3em gray; 
    }
}

However, for now, be wary of using @supports. By using it here we just limited our effect not only to browsers that support text shadows, but also to browsers that support the @supports rule—a much more limited set.

但在眼下,还必须慎用 @supports。在上面的例子中,我们想要的文本投影效果只会在那些支持 text-shadow 且同时支持 @supports 规则的浏览器中生效——这个范围明显比我们所期望的要窄。

Last, but not least, there is always the option of using a few lines of home-baked JavaScript to perform feature detection and add classes to the root element in the same fashion as Modernizr. The main way to determine whether a property is supported is to check its existence on the element.style object of any element:

最后,同样值得一提的是,即使你不打算使用 Modernizr,你也可以自己写一小段 JavaScript 代码来实现相同的功能——做一些特性检测然后给根元素加一些辅助类。如果要检测某个样式属性是否被支持,核心思路就是在任一元素的 element.style 对象上检查该属性是否存在:

var root = document.documentElement; // <html>

if ('textShadow' in root.style) { 
    root.classList.add('textshadow');
} 
else {
    root.classList.add('no-textshadow');
}

If we need to test for multiple properties, we can easily turn this into a function:

如果我们需要检测多个属性,也可以很容易地把上述代码改造成一个函数:

function testProperty(property) {
    var root = document.documentElement;

    if (property in root.style) { 
        root.classList.add(property.toLowerCase()); 
        return true;
    }

    root.classList.add('no-' + property.toLowerCase());
    return false; 
}

If we want to test a value, we need to assign it to the property and check if the browser retains it. Because we are modifying styles here and not just testing for their existence, it makes sense to use a dummy element:

如果我们想要检测某个具体的属性值是不是支持,那就需要把它赋给对应的属性,然后再检查浏览器是不是还保存着这个值。很显然,这个过程会改变元素的样式,因此我们需要用一个隐藏元素来做这件事情:

var dummy = document.createElement('p'); 
dummy.style.backgroundImage = 'linear-gradient(red,tan)';

if (dummy.style.backgroundImage) { 
    root.classList.add('lineargradients');
} 
else {
    root.classList.add('no-lineargradients');
}

This can easily be converted to a function as well:

这段代码同样也可以很容易地改造成一个函数:

function testValue(id, value, property) { 
    var dummy = document.createElement('p'); 
    dummy.style[property] = value;

    if (dummy.style[property]) { 
        root.classList.add(id); 
        return true;
    }

    root.classList.add('no-' + id);
    return false; 
}

Testing selectors and @rules is a bit more complex, but follows the same principle: when it comes to CSS, browsers drop anything they don’t understand, so we can check if a feature is recognized by dynamically applying it and checking if it was retained. Of course, keep in mind that a browser being able to parse a CSS feature offers no guarantee that the feature is correctly implemented, or even that it’s implemented at all.

如果要检测选择符和 @ 规则的支持情况,则会稍稍复杂一些。不过原理也很简单,在解析 CSS 代码时,浏览器总会丢弃它自己无法识别的部分,因此我们可以动态地应用样式并检查它是否生效,以此来判断浏览器是否可以识别某个特性。当然,我们也要清楚地认识到,浏览器可以解析某个 CSS 特性并不代表它已经实现(或正确实现)了这个特性

@riskers
Copy link

riskers commented Oct 14, 2015

什么时候出版啊

@cssmagic
Copy link
Owner Author

@riskers
我所掌握到的最新消息都会第一时间更新到 进度表

@cssmagic cssmagic mentioned this issue Oct 20, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants