Bootstrap

css参考手册css3手册_CSS手册:面向开发人员CSS便捷指南

css参考手册css3手册

I wrote this article to help you quickly learn CSS and get familiar with the advanced CSS topics.

我写这篇文章是为了帮助您快速学习CSS并熟悉高级CSS主题。

CSS is often quickly dismissed as an easy thing to learn by developers, or one thing you just pick up when you need to quickly style a page or app. Due to this reason, it’s often learned on-the-fly, or we learn things in isolation right when we have to use them. This can be a huge source of frustration when we find that the tool does not simply do what we want.

CSS通常很快就被开发人员轻松理解,或者当您需要快速设置页面或应用样式时,您会发现其中的一件事。 由于这个原因,它经常是动态学习的,或者当我们不得不使用它们时,我们会孤立地学习事物。 当我们发现该工具不能简单地完成我们想要的操作时,这可能是造成挫败感的巨大原因。

This article will help you get up to speed with CSS and get an overview of the main modern features you can use to style your pages and apps.

本文将帮助您快速了解CSS,并概述可用于设置页面和应用程序样式的主要现代功能。

I hope to help you get comfortable with CSS and get you quickly up to speed with using this awesome tool that lets you create stunning designs on the Web.

我希望可以帮助您熟悉CSS,并快速使用此超赞的工具来快速入门,该工具可让您在Web上创建出色的设计。

Click here to get a PDF / ePub / Mobi version of this post to read offline

点击此处获取该帖子的PDF / ePub / Mobi版本以离线阅读

CSS, a shorthand for Cascading Style Sheets, is one of the main building blocks of the Web. Its history goes back to the 90’s, and along with HTML it has changed a lot since its humble beginnings.

CSS是级联样式表的简写,是Web的主要构建块之一。 它的历史可以追溯到90年代,并且自HTML起步以来就与HTML一起发生了很大变化。

As I’ve been creating websites since before CSS existed, I have seen its evolution.

自从CSS诞生以来我就一直在创建网站,我已经看到了它的发展。

CSS is an amazing tool, and in the last few years it has grown a lot, introducing many fantastic features like CSS Grid, Flexbox and CSS Custom Properties.

CSS是一个了不起的工具,并且在最近几年中它发展了很多,引入了许多很棒的功能,例如CSS Grid,Flexbox和CSS Custom Properties。

This handbook is aimed at a vast audience.

本手册面向广大读者。

First, the beginner. I explain CSS from zero in a succinct but comprehensive way, so you can use this book to learn CSS from the basics.

首先是初学者。 我以简洁而全面的方式从零开始解释CSS,因此您可以使用本书从基础知识中学习CSS。

Then, the professional. CSS is often considered like a secondary thing to learn, especially by JavaScript developers. They know CSS is not a real programming language, they are programmers and therefore they should not bother learning CSS the right way. I wrote this book for you, too.

然后,专业。 CSS通常被视为次要学习的东西,特别是JavaScript开发人员。 他们知道CSS不是真正的编程语言,他们是程序员,因此,他们不应该为正确的方式学习CSS。 我也为你写过这本书。

Next, the person that knows CSS from a few years but hasn’t had the opportunity to learn the new things in it. We’ll talk extensively about the new features of CSS, the ones that are going to build the web of the next decade.

接下来,认识CSS的人已经有几年了,但是还没有机会学习其中的新知识。 我们将广泛讨论CSS的新功能,这些功能将用于构建下一个十年的网络。

CSS has improved a lot in the past few years and it’s evolving fast.

在过去的几年中,CSS取得了很大的进步,并且发展Swift。

Even if you don’t write CSS for a living, knowing how CSS works can help save you some headaches when you need to understand it from time to time, for example while tweaking a web page.

即使您不是为了谋生而编写CSS,了解CSS的工作原理也可以帮助您在需要时不时了解CSS的情况下(例如在调整网页时)避免头痛。

Thank you for getting this ebook. My goal with it is to give you a quick yet comprehensive overview of CSS.

感谢您获得此电子书。 我的目标是为您提供快速而全面CSS概述。

Flavio

弗拉维奥

You can reach me via email at [email protected], on Twitter @flaviocopes.

您可以通过[email protected]上的电子邮件 Twitter @flaviocopes与我联系

My website is flaviocopes.com.

我的网站是flaviocopes.com

目录 (Table of Contents)

CSS简介 (INTRODUCTION TO CSS)

CSS (an abbreviation of Cascading Style Sheets) is the language that we use to style an HTML file, and tell the browser how should it render the elements on the page.

CSS ( 层叠样式表 ( Cascading Style Sheets )的缩写)是我们用来设置HTML文件样式的语言,它告诉浏览器它应如何呈现页面上的元素。

In this book I talk exclusively about styling HTML documents, although CSS can be used to style other things too.

在本书中,我只讨论样式化HTML文档,尽管CSS也可以用于样式化其他内容。

A CSS file contains several CSS rules.

一个CSS文件包含几个CSS规则。

Each rule is composed by 2 parts:

每个规则由两部分组成:

  • the selector

    选择器

  • the declaration block

    声明块

The selector is a string that identifies one or more elements on the page, following a special syntax that we’ll soon talk about extensively.

选择器是一个字符串,用于标识页面上的一个或多个元素,并遵循一种特殊的语法,我们将在后面详细讨论。

The declaration block contains one or more declarations, in turn composed by a property and valuepair.

声明块包含一个或多个声明 ,依次由属性对组成。

Those are all the things we have in CSS.

这些就是我们在CSS中拥有的所有东西。

Carefully organising properties, associating them values, and attaching those to specific elements of the page using a selector is the whole argument of this ebook.

仔细组织属性,将它们的值相关联,并使用选择器将其附加到页面的特定元素是这本电子书的全部论点。

CSS看起来如何 (How does CSS look like)

A CSS rule set has one part called selector, and the other part called declaration. The declaration contains various rules, each composed by a property, and a value.

CSS 规则集的一部分称为选择器 ,另一部分称为声明 。 声明包含各种规则 ,每个规则由一个属性和一个值组成

In this example, p is the selector, and applies one rule which sets the value 20px to the font-size property:

在此示例中, p是选择器,并应用一个规则,该规则将20px的值设置为font-size属性:

p {
  font-size: 20px;
}

Multiple rules are stacked one after the other:

多个规则一个接一个地堆叠:

p {
  font-size: 20px;
}

a {
  color: blue;
}

A selector can target one or more items:

选择器可以定位一个或多个项目:

p, a {
  font-size: 20px;
}

and it can target HTML tags, like above, or HTML elements that contain a certain class attribute with .my-class, or HTML elements that have a specific id attribute with #my-id.

并且可以像上面那样定位HTML标记,也可以定位包含具有.my-class的特定类属性HTML元素,或定位具有#my-id的特定id属性HTML元素。

More advanced selectors allow you to choose items whose attribute matches a specific value, or also items which respond to pseudo-classes (more on that later)

使用更高级的选择器,您可以选择属性与特定值匹配的项,也可以选择对伪类作出响应的项(稍后会详细介绍)

分号 (Semicolons)

Every CSS rule terminates with a semicolon. Semicolons are not optional, except after the last rule. But I suggest to always use them for consistency and to avoid errors if you add another property and forget to add the semicolon on the previous line.

每个CSS规则都以分号结尾。 除最后一条规则外,分号不是可选的。 但是我建议始终使用它们来保持一致性,并避免错误(如果您添加了另一个属性而忘记在前一行添加分号)。

格式和缩进 (Formatting and indentation)

There is no fixed rule for formatting. This CSS is valid:

没有固定的格式化规则。 此CSS有效:

p
      {
  font-size:           20px   ;
                      }
                      
a{color:blue;}

but a pain to see. Stick to some conventions, like the ones you see in the examples above: stick selectors and the closing brackets to the left, indent 2 spaces for each rule, have the opening bracket on the same line of the selector, separated by one space.

但很痛苦。 遵循一些约定,如您在上面的示例中看到的那样:坚持选择器和左方括号,在每个规则上缩进2个空格,在选择器的同一行上将开始括号隔开一个空格。

Correct and consistent use of spacing and indentation is a visual aid in understanding your code.

正确,一致地使用间距和缩进有助于理解代码。

CSS的简要历史 (A BRIEF HISTORY OF CSS)

Before moving on, I want to give you a brief recap of the history of CSS.

在继续之前,我想简要回顾一下CSS的历史。

CSS was grown out of the necessity of styling web pages. Before CSS was introduced, people wanted a way to style their web pages, which looked all very similar and “academic” back in the day. You couldn’t do much in terms of personalisation.

CSS的产生是出于对网页样式的需要。 在引入CSS之前,人们想要一种样式化网页的方式,这些网页在当时看起来都非常相似且具有“学术性”。 就个性化而言,您不能做太多事情。

HTML 3.2 introduced the option of defining colors inline as HTML element attributes, and presentational tags like center and font, but that escalated quickly into a far from ideal situation.

HTML 3.2引入了将内联颜色定义为HTML元素属性以及表示性标签(例如centerfont ,但这种方法很快就升级到了理想的境地。

CSS let us move everything presentation-related from the HTML to the CSS, so that HTML could get back being the format that defines the structure of the document, rather than how things should look in the browser.

CSS使我们能够将所有与表示相关的内容从HTML移到CSS,以便HTML可以恢复为定义文档结构的格式,而不是浏览器中的外观。

CSS is continuously evolving, and CSS you used 5 years ago might just be outdated, as new idiomatic CSS techniques emerged and browsers changed.

CSS不断发展,随着新的惯用CSS技术的出现和浏览器的改变,您5年前使用CSS可能已经过时了。

It’s hard to imagine the times when CSS was born and how different the web was.

很难想象CSS诞生的时代以及网络的不同之处。

At the time, we had several competing browsers, the main ones being Internet Explorer or Netscape Navigator.

当时,我们有几种竞争的浏览器,主要的是Internet Explorer或Netscape Navigator。

Pages were styled by using HTML, with special presentational tags like bold and special attributes, most of which are now deprecated.

页面是使用HTML设置样式的,带有特殊的呈现标记,例如bold和特殊属性,现在已弃用了其中的大多数标记。

This meant you had a limited amount of customisation opportunities.

这意味着您的定制机会有限。

The bulk of the styling decisions were left to the browser.

大部分样式决定留给浏览器。

Also, you built a site specifically for one of them, because each one introduced different non-standard tags to give more power and opportunities.

另外,您为其中一个站点专门构建了一个站点,因为每个站点都引入了不同的非标准标签以提供更多功能和机会。

Soon people realised the need for a way to style pages, in a way that would work across all browsers.

很快,人们意识到了一种需要在所有浏览器上都可以使用的样式页面的方法。

After the initial idea proposed in 1994, CSS got its first release in 1996, when the CSS Level 1 (“CSS 1”) recommendation was published.

在1994年提出最初的想法后,CSS于1996年发布了CSS Level 1(“ CSS 1”)建议书,并首次发布。

CSS Level 2 (“CSS 2”) got published in 1998.

CSS Level 2(“ CSS 2”)于1998年发布。

Since then, work began on CSS Level 3. The CSS Working Group decided to split every feature and work on it separately, in modules.

从那时起,就开始了CSS级别3的工作。CSS工作组决定将每个功能拆分并分别在模块中进行。

Browsers weren’t especially fast at implementing CSS. We had to wait until 2002 to have the first browser implement the full CSS specification: IE for Mac, as nicely described in this CSS Tricks post: https://css-tricks.com/look-back-history-css/

浏览器在实现CSS方面并不是特别快。 我们必须等到2002年,才能使第一个浏览器实现完整CSS规范:适用于Mac的IE,如本CSS Tricks帖子中所描述的: https//css-tricks.com/look-back-history-css/

Internet Explorer implemented the box model incorrectly right from the start, which led to years of pain trying to have the same style applied consistently across browsers. We had to use various tricks and hacks to make browsers render things as we wanted.

Internet Explorer从一开始就错误地实现了框模型,这导致多年来试图在浏览器中始终使用相同样式的痛苦。 我们必须使用各种技巧和黑客手段来使浏览器呈现所需的东西。

Today things are much, much better. We can just use the CSS standards without thinking about quirks, most of the time, and CSS has never been more powerful.

今天的情况好多了。 大多数情况下,我们无需考虑怪癖就可以使用CSS标准,而CSS从未如此强大。

We don’t have official release numbers for CSS any more now, but the CSS Working Group releases a “snapshot” of the modules that are currently considered stable and ready to be included in browsers. This is the latest snapshot, from 2018: https://www.w3.org/TR/css-2018/

我们现在没有CSS的正式发布号,但是CSS工作组发布了一些模块的“快照”,这些模块目前被认为是稳定的并且可以包含在浏览器中。 这是自2018年以来的最新快照: https//www.w3.org/TR/css-2018/

CSS Level 2 is still the base for the CSS we write today, and we have many more features built on top of it.

CSS Level 2仍然是我们今天编写CSS的基础,并且我们在其之上构建了更多功能。

将CSS添加到HTML页面 (ADDING CSS TO AN HTML PAGE)

CSS is attached to an HTML page in different ways.

CSS以不同方式附加到HTML页面。

The link tag is the way to include a CSS file. This is the preferred way to use CSS as it's intended to be used: one CSS file is included by all the pages of your site, and changing one line on that file affects the presentation of all the pages in the site.

link标记是包含CSS文件的方式。 这是按预期使用CSS的首选方式:站点的所有页面都包含一个CSS文件,更改该文件的一行会影响站点中所有页面的显示。

To use this method, you add a link tag with the href attribute pointing to the CSS file you want to include. You add it inside the head tag of the site (not inside the body tag):

要使用此方法,请添加一个带有href属性的link标签,该标签指向要包含CSS文件。 您将其添加到网站的head标签中(而不是body标签中):

<link rel="stylesheet" type="text/css" href="myfile.css">

The rel and type attributes are required too, as they tell the browser which kind of file we are linking to.

reltype属性也是必需的,因为它们告诉浏览器我们要链接到哪种文件。

2:使用style标签 (2: using the style tag)

Instead of using the link tag to point to separate stylesheet containing our CSS, we can add the CSS directly inside a style tag. This is the syntax:

无需使用link标记指向包含我们CSS的单独样式表,而是可以将CSS直接添加到style标记中。 这是语法:

<style>
...our CSS...
</style>

Using this method we can avoid creating a separate CSS file. I find this is a good way to experiment before “formalising” CSS to a separate file, or to add a special line of CSS just to a file.

使用这种方法,我们可以避免创建单独CSS文件。 我发现这是一种在将CSS“形式化”到单独文件之前进行实验或在文件中添加一行特殊CSS的好方法。

3:内联样式 (3: inline styles)

Inline styles are the third way to add CSS to a page. We can add a style attribute to any HTML tag, and add CSS into it.

内联样式是将CSS添加到页面的第三种方法。 我们可以将style属性添加到任何HTML标记,然后在其中添加CSS。

<div style="">...</div>

Example:

例:

<div style="background-color: yellow">...</div>

选择者 (SELECTORS)

A selector allows us to associate one or more declarations to one or more elements on the page.

选择器使我们可以将一个或多个声明与页面上的一个或多个元素相关联。

基本选择器 (Basic selectors)

Suppose we have a p element on the page, and we want to display the words into it using the yellow color.

假设我们在页面上有一个p元素,并且我们想用黄色将单词显示在其中。

We can target that element using this selector p, which targets all the element using the p tag in the page. A simple CSS rule to achieve what we want is:

我们可以针对使用该选择器元素p ,瞄准所有使用的元素p在页面标签。 实现我们想要的简单CSS规则是:

p {
  color: yellow;
}

Every HTML tag has a corresponding selector, for example: div, span, img.

每个HTML标签都有一个对应的选择器,例如: divspanimg

If a selector matches multiple elements, all the elements in the page will be affected by the change.

如果选择器与多个元素匹配,则页面中的所有元素都会受到更改的影响。

HTML elements have 2 attributes which are very commonly used within CSS to associate styling to a specific element on the page: class and id.

HTML元素具有2个属性,它们在CSS中非常常用于将样式与页面上的特定元素相关联: classid

There is one big difference between those two: inside an HTML document you can repeat the same class value across multiple elements, but you can only use an id once. As a corollary, using classes you can select an element with 2 or more specific class names, something not possible using ids.

两者之间有一个很大的区别:在HTML文档中,您可以跨多个元素重复相同的class值,但是只能使用一次id 。 因此,使用类可以选择具有2个或更多个特定类名的元素,而使用id则无法实现。

Classes are identified using the . symbol, while ids using the # symbol.

使用标识类. 符号,而id使用#符号。

Example using a class:

使用类的示例:

<p class="dog-name">
  Roger
</p>

.dog-name {
  color: yellow;
}

Example using an id:

使用ID的示例:

<p id="dog-name">
  Roger
</p>

#dog-name {
  color: yellow;
}
组合选择器 (Combining selectors)

So far we’ve seen how to target an element, a class or an id. Let’s introduce more powerful selectors.

到目前为止,我们已经了解了如何定位元素,类或ID。 让我们介绍更强大的选择器。

使用类或ID定位元素 (Targeting an element with a class or id)

You can target a specific element that has a class, or id, attached.

您可以定位附加了类或ID的特定元素。

Example using a class:

使用类的示例:

<p class="dog-name">
  Roger
</p>

p.dog-name {
  color: yellow;
}

Example using an id:

使用ID的示例:

<p id="dog-name">
  Roger
</p>

p#dog-name {
  color: yellow;
}

Why would you want to do that, if the class or id already provides a way to target that element? You might have to do that to have more specificity. We’ll see what that means later.

如果类或id已经提供了一种针对该元素的方法,那么为什么要这么做呢? 您可能需要这样做才能具有更多的特异性。 稍后我们将了解这意味着什么。

针对多个类别 (Targeting multiple classes)

You can target an element with a specific class using .class-name, as you saw previously. You can target an element with 2 (or more) classes by combining the class names separated with a dot, without spaces.

如前所述,您可以使用.class-name定位具有特定类的元素。 通过组合用点分隔的类名(不带空格),可以将元素指定为2个(或更多)类。

Example:

例:

<p class="dog-name roger">
  Roger
</p>

.dog-name.roger {
  color: yellow;
}
结合类和ID (Combining classes and ids)

In the same way, you can combine a class and an id.

同样,您可以组合一个类和一个id。

Example:

例:

<p class="dog-name" id="roger">
  Roger
</p>

.dog-name#roger {
  color: yellow;
}
分组选择器 (Grouping selectors)

You can combine selectors to apply the same declarations to multiple selectors. To do so, you separate them with a comma.

您可以组合选择器以将相同的声明应用于多个选择器。 为此,请用逗号分隔它们。

Example:

例:

<p>
  My dog name is:
</p>
<span class="dog-name">
  Roger
</span>

p, .dog-name {
  color: yellow;
}

You can add spaces in those declarations to make them more clear:

您可以在这些声明中添加空格以使其更清晰:

p,
.dog-name {
  color: yellow;
}
使用选择器跟随文档树 (Follow the document tree with selectors)

We’ve seen how to target an element in the page by using a tag name, a class or an id.

我们已经了解了如何通过使用标签名称,类或ID来定位页面中的元素。

You can create a more specific selector by combining multiple items to follow the document tree structure. For example, if you have a span tag nested inside a p tag, you can target that one without applying the style to a span tag not included in a p tag:

您可以通过组合多个项目来遵循文档树结构来创建更具体的选择器。 举例来说,如果你有一个span嵌套在一个标记内p标签,你就可以指定一个不应用样式,以一个span不包括在标签p标签:

<span>
  Hello!
</span>
<p>
  My dog name is:
  <span class="dog-name">
    Roger
  </span>
</p>

p span {
  color: yellow;
}

See how we used a space between the two tokens p and span.

看看我们如何在两个标记pspan之间使用空格。

This works even if the element on the right is multiple levels deep.

即使右侧的元素深达多个级别,此方法也有效。

To make the dependency strict on the first level, you can use the > symbol between the two tokens:

为了使依赖性严格地处于第一级,可以在两个标记之间使用>符号:

p > span {
  color: yellow;
}

In this case, if a span is not a first children of the p element, it's not going to have the new color applied.

在这种情况下,如果span不是p元素的第一p元素,则不会应用新颜色。

Direct children will have the style applied:

直接的孩子将应用以下样式:

<p>
  <span>
    This is yellow
  </span>
  <strong>
    <span>
      This is not yellow
    </span>
  </strong>
</p>

Adjacent sibling selectors let us style an element only if preceded by a specific element. We do so using the + operator:

相邻的同级选择器使我们仅在元素前面有特定元素的情况下才能为其设置样式。 我们使用+运算符:

Example:

例:

p + span {
  color: yellow;
}

This will assign the color yellow to all span elements preceded by a p element:

这会将黄色分配给所有以p元素开头的p元素:

<p>This is a paragraph</p>
<span>This is a yellow span</span>

We have a lot more selectors we can use:

我们可以使用更多选择器:

  • attribute selectors

    属性选择器
  • pseudo class selectors

    伪类选择器
  • pseudo element selectors

    伪元素选择器

We’ll find all about them in the next sections.

我们将在下一部分中找到有关它们的所有信息。

级联 (CASCADE)

Cascade is a fundamental concept of CSS. After all, it’s in the name itself, the first C of CSS — Cascading Style Sheets — it must be an important thing.

级联是CSS的基本概念。 毕竟,它的名字本身就是CSS的第一个C语言(层叠样式表),它必须是一件重要的事情。

What does it mean?

这是什么意思?

Cascade is the process, or algorithm, that determines the properties applied to each element on the page. Trying to converge from a list of CSS rules that are defined in various places.

级联是确定应用于页面上每个元素的属性的过程或算法。 尝试从各地定义CSS规则列表中收敛。

It does so taking in consideration:

这样做时考虑到:

  • specificity

    特异性
  • importance

    重要性
  • inheritance

    遗产
  • order in the file

    在文件中排序

It also takes care of resolving conflicts.

它还负责解决冲突。

Two or more competing CSS rules for the same property applied to the same element need to be elaborated according to the CSS spec, to determine which one needs to be applied.

需要根据CSS规范为适用于同一元素的相同属性制定两个或多个竞争CSS规则,以确定需要应用哪一个。

Even if you just have one CSS file loaded by your page, there is other CSS that is going to be part of the process. We have the browser (user agent) CSS. Browsers come with a default set of rules, all different between browsers.

即使您的页面仅加载了一个CSS文件,其他CSS也将成为该过程的一部分。 我们有浏览器(用户代理)CSS。 浏览器带有一组默认规则,所有浏览器之间都有所不同。

Then your CSS comes into play.

然后您CSS开始起作用。

Then the browser applies any user stylesheet, which might also be applied by browser extensions.

然后,浏览器将应用任何用户样式表,浏览器扩展也可能会应用该样式表。

All those rules come into play while rendering the page.

所有这些规则在呈现页面时都会起作用。

We’ll now see the concepts of specificity and inheritance.

现在,我们将看到特异性和继承性的概念。

特殊性 (SPECIFICITY)

What happens when an element is targeted by multiple rules, with different selectors, that affect the same property?

当一个元素被多个规则,具有不同选择器的,影响同一属性的目标定位时,会发生什么?

For example, let’s talk about this element:

例如,让我们谈谈这个元素:

<p class="dog-name">
  Roger
</p>

We can have

我们可以有

.dog-name {
  color: yellow;
}

and another rule that targets p, which sets the color to another value:

另一个针对p规则,它将颜色设置为另一个值:

p {
  color: red;
}

And another rule that targets p.dog-name. Which rule is going to take precedence over the others, and why?

另一个针对p.dog-name规则。 哪个规则将优先于其他规则,为什么?

Enter specificity. The more specific rule will win. If two or more rules have the same specificity, the one that appears last wins.

输入特异性。 更具体的规则将获胜 。 如果两个或多个规则具有相同的特异性,则最后出现的那个将获胜

Sometimes what is more specific in practice is a bit confusing to beginners. I would say it’s also confusing to experts that do not look at those rules that frequently, or simply overlook them.

有时,实践中更具体的内容对于初学者来说有些混乱。 我要说的是,那些不经常查看或忽略这些规则的专家也会感到困惑。

如何计算特异性 (How to calculate specificity)

Specificity is calculated using a convention.

使用惯例计算特异性。

We have 4 slots, and each one of them starts at 0: 0 0 0 0 0. The slot at the left is the most important, and the rightmost one is the least important.

我们有4个插槽,每个插槽都从0: 0 0 0 0 0 。 左侧的插槽最重要,最右侧的插槽最不重要。

Like it works for numbers in the decimal system: 1 0 0 0 is higher than 0 1 0 0.

就像它适用于十进制系统中的数字一样: 1 0 0 0高于0 1 0 0

插槽1 (Slot 1)

The first slot, the rightmost one, is the least important.

最右边的插槽是最不重要的插槽。

We increase this value when we have an element selector. An element is a tag name. If you have more than one element selector in the rule, you increment accordingly the value stored in this slot.

当我们有一个元素选择器时,我们增加这个值。 元素是标签名称。 如果规则中有多个元素选择器,则相应地增加此插槽中存储的值。

Examples:

例子:

p {}                    /* 0 0 0 1 */
span {}                 /* 0 0 0 1 */
p span {}               /* 0 0 0 2 */
p > span {}             /* 0 0 0 2 */
div p > span {}         /* 0 0 0 3 */
插槽2 (Slot 2)

The second slot is incremented by 3 things:

第二个插槽增加3个位:

  • class selectors

    类选择器
  • pseudo-class selectors

    伪类选择器
  • attribute selectors

    属性选择器

Every time a rule meets one of those, we increment the value of the second column from the right.

每当规则满足其中一个条件时,我们就会从右边开始增加第二列的值。

Examples:

例子:

.name {}                 /* 0 0 1 0 */
.users .name {}          /* 0 0 2 0 */
[href$='.pdf'] {}        /* 0 0 1 0 */
:hover {}                /* 0 0 1 0 */

Of course slot 2 selectors can be combined with slot 1 selectors:

当然,插槽2选择器可以与插槽1选择器结合使用:

div .name {}             /* 0 0 1 1 */
a[href$='.pdf'] {}       /* 0 0 1 1 */
.pictures img:hover {}   /* 0 0 2 1 */

One nice trick with classes is that you can repeat the same class and increase the specificity. For example:

类的一个不错的技巧是,您可以重复相同的类并增加特异性。 例如:

.name {}              /* 0 0 1 0 */
.name.name {}         /* 0 0 2 0 */
.name.name.name {}    /* 0 0 3 0 */
插槽3 (Slot 3)

Slot 3 holds the most important thing that can affect your CSS specificity in a CSS file: the id.

插槽3在CSS文件中保留了可能影响CSS特异性的最重要的内容: id

Every element can have an id attribute assigned, and we can use that in our stylesheet to target the element.

每个元素都可以分配一个id属性,我们可以在样式表中使用它来定位该元素。

Examples:

例子:

#name {}                    /* 0 1 0 0 */
.user #name {}              /* 0 1 1 0 */
#name span {}               /* 0 1 0 1 */
插槽4 (Slot 4)

Slot 4 is affected by inline styles. Any inline style will have precedence over any rule defined in an external CSS file, or inside the style tag in the page header.

广告位4受内联样式的影响。 任何内联样式都将优先于外部CSS文件或页面标题中的style标签内定义的任何规则。

Example:

例:

<p style="color: red">Test</p> /* 1 0 0 0 */

Even if any other rule in the CSS defines the color, this inline style rule is going to be applied. Except for one case — if !important is used, which fills the slot 5.

即使CSS中的任何其他规则定义了颜色,也将应用此内联样式规则。 除一种情况外-如果使用!important ,则填充插槽5。

重要性 (Importance)

Specificity does not matter if a rule ends with !important:

规则是否以!important结尾并不!important

p {
  font-size: 20px!important;
}

That rule will take precedence over any rule with more specificity

该规则将优先于任何更具体的规则

Adding !important in a CSS rule is going to make that rule more important than any other rule, according to the specificity rules. The only way another rule can take precedence is to have !important as well, and have higher specificity in the other less important slots.

根据特殊性规则,在CSS规则中添加!important将使该规则比其他任何规则都更加重要。 另一个规则可以优先的唯一方法就是也要具有!important ,并且在其他不那么重要的广告位中具有更高的特异性。

提示 (Tips)

In general you should use the amount of specificity you need, but not more. In this way, you can craft other selectors to overwrite the rules set by preceding rules without going mad.

通常,您应该使用所需的特异性,但不能更多。 这样,您可以精心制作其他选择器以覆盖之前的规则设置的规则,而不会发疯。

!important is a highly debated tool that CSS offers us. Many CSS experts advocate against using it. I find myself using it especially when trying out some style and a CSS rule has so much specificity that I need to use !important to make the browser apply my new CSS.

!important是CSS为我们提供的备受争议的工具。 许多CSS专家主张不要使用它。 我发现自己正在使用它,尤其是在尝试某种样式时,并且CSS规则具有如此高的特异性,以至于我需要使用!important来使浏览器应用我的新CSS。

But generally, !important should have no place in your CSS files.

但通常, !important在CSS文件中不应放置任何位置。

Using the id attribute to style CSS is also debated a lot, since it has a very high specificity. A good alternative is to use classes instead, which have less specificity, and so they are easier to work with, and they are more powerful (you can have multiple classes for an element, and a class can be reused multiple times).

使用id属性设置CSS样式也存在很多争议,因为它具有很高的特异性。 一个很好的选择是使用类,因为它们的特异性较低,因此更易于使用,并且功能更强大(您可以为一个元素使用多个类,并且一个类可以多次重用)。

计算特异性的工具 (Tools to calculate the specificity)

You can use the site https://specificity.keegan.st/ to perform the specificity calculation for you automatically.

您可以使用网站https://specificity.keegan.st/自动为您执行特异性计算。

It’s useful especially if you are trying to figure things out, as it can be a nice feedback tool.

这特别有用,尤其是在您尝试解决问题时,因为它可能是一个不错的反馈工具。

遗产 (INHERITANCE)

When you set some properties on a selector in CSS, they are inherited by all the children of that selector.

在CSS中的选择器上设置某些属性时,该属性将由该选择器的所有子级继承。

I said some, because not all properties show this behaviour.

我说了一些 ,因为并非所有属性都显示此行为。

This happens because some properties make sense to be inherited. This helps us write CSS much more concisely, since we don’t have to explicitly set that property again on every single child.

发生这种情况是因为可以继承某些属性。 这有助于我们更加简洁地编写CSS,因为我们不必在每个孩子上都再次显式设置该属性。

Some other properties make more sense to not be inherited.

继承某些其他属性更有意义。

Think about fonts: you don’t need to apply the font-family to every single tag of your page. You set the body tag font, and every child inherits it, along with other properties.

考虑一下字体:您无需将font-family应用于页面的每个标签。 设置body标记字体,每个子代都会继承它,以及其他属性。

The background-color property, on the other hand, makes little sense to be inherited.

另一方面, background-color属性几乎没有意义。

继承的属性 (Properties that inherit)

Here is a list of the properties that do inherit. The list is non-comprehensive, but those rules are just the most popular ones you’ll likely use:

这是确实继承的属性的列表。 该列表并不全面,但是这些规则只是您可能会使用的最受欢迎的规则:

  • border-collapse

    边界崩溃
  • border-spacing

    边界间距
  • caption-side

    字幕端
  • color

    颜色
  • cursor

    光标
  • direction

    方向
  • empty-cells

    空单元格
  • font-family

    字体系列
  • font-size

    字体大小
  • font-style

    字体样式
  • font-variant

    字体变体
  • font-weight

    字体粗细
  • font-size-adjust

    字体大小调整
  • font-stretch

    字体拉伸
  • font

    字形
  • letter-spacing

    字母间距
  • line-height

    行高
  • list-style-image

    列表样式图像
  • list-style-position

    列表样式位置
  • list-style-type

    列表样式类型
  • list-style

    列表样式
  • orphans

    孤儿
  • quotes

    引号
  • tab-size

    标签大小
  • text-align

    文字对齐
  • text-align-last

    文本最后对齐
  • text-decoration-color

    文字装饰颜色
  • text-indent

    文字缩进
  • text-justify

    文字对齐
  • text-shadow

    文字阴影
  • text-transform

    文字转换
  • visibility

    能见度
  • white-space

    空格
  • widows

    寡妇
  • word-break

    断字
  • word-spacing

    字距

I got it from this nice Sitepoint article on CSS inheritance.

我从有关CSS继承的这篇不错的Sitepoint文章中获得了它。

强制属性继承 (Forcing properties to inherit)

What if you have a property that’s not inherited by default, and you want it to, in a child?

如果您的孩子有一个默认情况下不继承的属性,该怎么办?

In the children, you set the property value to the special keyword inherit.

在子级中,将属性值设置为特殊关键字inherit

Example:

例:

body {
    background-color: yellow;
}

p {
  background-color: inherit;
}
强制属性不继承 (Forcing properties to NOT inherit)

On the contrary, you might have a property inherited and you want to avoid so.

相反,您可能继承了一个属性,但要避免这种情况。

You can use the revert keyword to revert it. In this case, the value is reverted to the original value the browser gave it in its default stylesheet.

您可以使用revert关键字将其还原。 在这种情况下,该值将还原为浏览器在其默认样式表中为其提供的原始值。

In practice this is rarely used, and most of the times you’ll just set another value for the property to overwrite that inherited value.

实际上,这很少使用,大多数情况下,您将为属性设置另一个值以覆盖该继承的值。

其他特殊值 (Other special values)

In addition to the inherit and revert special keywords we just saw, you can also set any property to:

除了我们刚刚看到的inheritrevert特殊关键字之外,您还可以将任何属性设置为:

  • initial: use the default browser stylesheet if available. If not, and if the property inherits by default, inherit the value. Otherwise do nothing.

    initial :使用默认的浏览器样式表(如果有)。 如果不是,并且该属性默认继承,则继承该值。 否则什么都不做。

  • unset: if the property inherits by default, inherit. Otherwise do nothing.

    unset :如果属性默认继承,则继承。 否则什么都不做。

进口 (IMPORT)

From any CSS file you can import another CSS file using the @import directive.

从任何CSS文件中,您都可以使用@import指令导入另一个CSS文件。

Here is how you use it:

使用方法如下:

@import url(myfile.css)

url() can manage absolute or relative URLs.

url()可以管理绝对或相对URL。

One important thing you need to know is that @import directives must be put before any other CSS in the file, or they will be ignored.

您需要知道的一件事是@import指令必须放在文件中的任何其他CSS之前,否则它们将被忽略。

You can use media descriptors to only load a CSS file on the specific media:

您可以使用媒体描述符在特定媒体上仅加载CSS文件:

@import url(myfile.css) all;
@import url(myfile-screen.css) screen;
@import url(myfile-print.css) print;

属性选择器 (ATTRIBUTE SELECTORS)

We already introduced several of the basic CSS selectors: using element selectors, class, id, how to combine them, how to target multiple classes, how to style several selectors in the same rule, how to follow the page hierarchy with child and direct child selectors, and adjacent siblings.

我们已经介绍了几个基本CSS选择器:使用元素选择器,类,id,如何组合它们,如何定位多个类,如何在同一规则中设置多个选择器样式,如何在子层次结构和直接子层次结构之间遵循页面层次结构选择器和相邻的兄弟姐妹。

In this section we’ll analyze attribute selectors, and we’ll talk about pseudo class and pseudo element selectors in the next 2 sections.

在本节中,我们将分析属性选择器,并在接下来的2部分中讨论伪类和伪元素选择器。

属性存在选择器 (Attribute presence selectors)

The first selector type is the attribute presence selector.

第一种选择器类型是属性存在选择器。

We can check if an element has an attribute using the [] syntax. p[id] will select all p tags in the page that have an id attribute, regardless of its value:

我们可以使用[]语法检查元素是否具有属性。 p[id]将选择页面中具有id属性的所有p标记,无论其值如何:

p[id] {
  /* ... */
}
确切的属性值选择器 (Exact attribute value selectors)

Inside the brackets you can check the attribute value using =, and the CSS will be applied only if the attribute matches the exact value specified:

在方括号内,您可以使用=检查属性值,并且仅当属性与指定的确切值匹配时,才会应用CSS:

p[id="my-id"] {
  /* ... */
}
匹配属性值部分 (Match an attribute value portion)

While = lets us check for exact value, we have other operators:

虽然=让我们检查确切值,但我们还有其他运算符:

  • *= checks if the attribute contains the partial

    *=检查属性是否包含部分

  • ^= checks if the attribute starts with the partial

    ^=检查属性是否以局部变量开头

  • $= checks if the attribute ends with the partial

    $=检查属性是否以部分结尾

  • |= checks if the attribute starts with the partial and it's followed by a dash (common in classes, for example), or just contains the partial

    |=检查属性是否以partial开始,并在其后跟一个破折号(例如,在类中很常见),或者仅包含partial

  • ~= checks if the partial is contained in the attribute, but separated by spaces from the rest

    ~=检查部分属性是否包含在属性中,但其余部分之间用空格分隔

All the checks we mentioned are case sensitive.

我们提到的所有检查都是区分大小写的

If you add an i just before the closing bracket, the check will be case insensitive. It's supported in many browsers but not in all, check https://caniuse.com/#feat=css-case-insensitive.

如果在右括号之前添加i ,则该检查将不区分大小写。 许多浏览器都支持它,但并非所有浏览器都支持,请检查https://caniuse.com/#feat=css-case-insensitive

假类 (PSEUDO-CLASSES)

Pseudo classes are predefined keywords that are used to select an element based on its state, or to target a specific child.

伪类是预定义的关键字,用于根据元素的状态选择元素或以特定的子对象为目标。

They start with a single colon :.

它们以单个冒号开始:

They can be used as part of a selector, and they are very useful to style active or visited links, for example, change the style on hover, focus, or target the first child, or odd rows. Very handy in many cases.

它们可以用作选择器的一部分,它们对于设置活动或访问链接的样式非常有用,例如,在悬停时更改样式,将焦点对准或定位第一个子对象或奇数行。 在许多情况下非常方便。

These are the most popular pseudo classes you will likely use:

这些是您可能会使用的最受欢迎的伪类:

Let’s do an example. A common one, actually. You want to style a link, so you create a CSS rule to target the a element:

让我们做一个例子。 实际上,这是常见的一种。 您想要设置链接的样式,因此创建一个CSS规则以a元素为目标:

a {
  color: yellow;
}

Things seem to work fine, until you click one link. The link goes back to the predefined color (blue) when you click it. Then when you open the link and go back to the page, now the link is blue.

一切正常,直到您单击一个链接。 单击链接后,该链接将返回到预定义的颜色(蓝色)。 然后,当您打开链接并返回页面时,现在链接为蓝色。

Why does that happen?

为什么会这样呢?

Because the link when clicked changes state, and goes in the :active state. And when it's been visited, it is in the :visited state. Forever, until the user clears the browsing history.

因为单击链接时会更改状态,并进入:active状态。 当它被访问时,它处于:visited状态。 直到用户清除浏览历史记录为止。

So, to correctly make the link yellow across all states, you need to write

因此,要使所有状态的链接正确变为黄色,您需要编写

a,
;