博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
css参考手册css3手册_CSS手册:面向开发人员CSS便捷指南
阅读量:2529 次
发布时间:2019-05-11

本文共 185671 字,大约阅读时间需要 618 分钟。

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上创建出色的设计。

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 , on Twitter .

您可以通过上的电子邮件 Twitter 。

My website is .

我的网站是 。

目录 (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:

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

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:

我们现在没有CSS的正式发布号,但是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标签中):

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标记中。 这是语法:

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。

...

Example:

例:

...

选择者 (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:

使用类的示例:

Roger

.dog-name { color: yellow;}

Example using an id:

使用ID的示例:

Roger

#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:

使用类的示例:

Roger

p.dog-name { color: yellow;}

Example using an id:

使用ID的示例:

Roger

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:

例:

Roger

.dog-name.roger { color: yellow;}

结合类和ID (Combining classes and ids)

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

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

Example:

例:

Roger

.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:

例:

My dog name is:

Rogerp, .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标签:

  Hello!

My dog name is: Roger

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:

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

This is yellow This is not yellow

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元素:

This is a paragraph

This is a yellow 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:

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

Roger

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:

例:

Test

/* 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 to perform the specificity calculation for you automatically.

您可以使用网站自动为您执行特异性计算。

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 on CSS inheritance.

我从有关CSS继承的这篇获得了它。

强制属性继承 (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 .

如果在右括号之前添加i ,则该检查将不区分大小写。 许多浏览器都支持它,但并非所有浏览器都支持,请检查 。

假类 (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,a:visited,a:active {  color: yellow;}

:nth-child() deserves a special mention. It can be used to target odd or even children with :nth-child(odd) and :nth-child(even).

:nth-child()特别值得一提。 它可以用于:nth-child(odd):nth-child(even)奇数或偶数子目标。

It is commonly used in lists to color odd lines differently from even lines:

它通常用于列表中,以奇数行和偶数行不同的颜色:

ul:nth-child(odd) {  color: white;    background-color: black;}

You can also use it to target the first 3 children of an element with :nth-child(-n+3). Or you can style 1 in every 5 elements with :nth-child(5n).

您还可以使用:nth-child(-n+3)来定位元素的:nth-child(-n+3) 。 或者,您可以使用:nth-child(5n)在每5个元素中设置1个样式。

Some pseudo classes are just used for printing, like :first, :left, :right, so you can target the first page, all the left pages, and all the right pages, which are usually styled slightly differently.

一些伪类仅用于打印,例如:first:left:right ,因此您可以定位首页,所有左侧页面和所有右侧页面,它们的样式通常略有不同。

伪元素 (PSEUDO-ELEMENTS)

伪元素用于设置元素的特定部分的样式。 (Pseudo-elements are used to style a specific part of an element.)

They start with a double colon ::.

它们以双冒号::开头。

Sometimes you will spot them in the wild with a single colon, but this is only a syntax supported for backwards compatibility reasons. You should use 2 colons to distinguish them from pseudo-classes.

有时,您可能会发现它们只是一个冒号而已,但是出于向后兼容的原因,这仅是一种受支持的语法。 您应该使用2个冒号将它们与伪类区分开。

::before and ::after are probably the most used pseudo-elements. They are used to add content before or after an element, like icons for example.

::before::after可能是最常用的伪元素。 它们用于在元素之前或之后添加内容,例如图标。

Here’s the list of the pseudo-elements:

这是伪元素的列表:

Let’s do an example. Say you want to make the first line of a paragraph slightly bigger in font size, a common thing in typography:

让我们做一个例子。 假设您要使段落的第一行的字体大小稍大一些,这在排版中很常见:

p::first-line {  font-size: 2rem;}

Or maybe you want the first letter to be bolder:

或者,也许您希望第一个字母更大胆:

p::first-letter {  font-weight: bolder;}

::after and ::before are a bit less intuitive. I remember using them when I had to add icons using CSS.

::after::before不太直观。 我记得当我不得不使用CSS添加图标时使用它们。

You specify the content property to insert any kind of content after or before an element:

您可以指定content属性以在元素之后或之前插入任何类型的内容:

p::before {  content: url(/myimage.png);}.myElement::before {    content: "Hey Hey!";}

颜色 (COLORS)

By default an HTML page is rendered by web browsers quite sadly in terms of the colors used.

默认情况下,就使用的颜色而言,Web浏览器呈现HTML页面非常可悲。

We have a white background, black color, and blue links. That’s it.

我们有白色背景,黑色和蓝色链接。 而已。

Luckily CSS gives us the ability to add colors to our designs.

幸运的是,CSS使我们能够在设计中添加颜色。

We have these properties:

我们具有以下属性:

  • color

    color

  • background-color

    background-color

  • border-color

    border-color

All of them accept a color value, which can be in different forms.

它们都接受一个可以采用不同形式的颜色值

命名的颜色 (Named colors)

First, we have CSS keywords that define colors. CSS started with 16, but today there is a huge number of colors names:

首先,我们有定义颜色CSS关键字。 CSS从16开始,但是今天有很多颜色名称:

  • aliceblue

    aliceblue

  • antiquewhite

    antiquewhite

  • aqua

    aqua

  • aquamarine

    aquamarine

  • azure

    azure

  • beige

    beige

  • bisque

    bisque

  • black

    black

  • blanchedalmond

    blanchedalmond

  • blue

    blue

  • blueviolet

    blueviolet

  • brown

    brown

  • burlywood

    burlywood

  • cadetblue

    cadetblue

  • chartreuse

    chartreuse

  • chocolate

    chocolate

  • coral

    coral

  • cornflowerblue

    cornflowerblue

  • cornsilk

    cornsilk

  • crimson

    crimson

  • cyan

    cyan

  • darkblue

    darkblue

  • darkcyan

    darkcyan

  • darkgoldenrod

    darkgoldenrod

  • darkgray

    darkgray

  • darkgreen

    darkgreen

  • darkgrey

    darkgrey

  • darkkhaki

    darkkhaki

  • darkmagenta

    darkmagenta

  • darkolivegreen

    darkolivegreen

  • darkorange

    darkorange

  • darkorchid

    darkorchid

  • darkred

    darkred

  • darksalmon

    darksalmon

  • darkseagreen

    darkseagreen

  • darkslateblue

    darkslateblue

  • darkslategray

    darkslategray

  • darkslategrey

    darkslategrey

  • darkturquoise

    darkturquoise

  • darkviolet

    darkviolet

  • deeppink

    deeppink

  • deepskyblue

    deepskyblue

  • dimgray

    dimgray

  • dimgrey

    dimgrey

  • dodgerblue

    dodgerblue

  • firebrick

    firebrick

  • floralwhite

    floralwhite

  • forestgreen

    forestgreen

  • fuchsia

    fuchsia

  • gainsboro

    gainsboro

  • ghostwhite

    ghostwhite

  • gold

    gold

  • goldenrod

    goldenrod

  • gray

    gray

  • green

    green

  • greenyellow

    greenyellow

  • grey

    grey

  • honeydew

    honeydew

  • hotpink

    hotpink

  • indianred

    indianred

  • indigo

    indigo

  • ivory

    ivory

  • khaki

    khaki

  • lavender

    lavender

  • lavenderblush

    lavenderblush

  • lawngreen

    lawngreen

  • lemonchiffon

    lemonchiffon

  • lightblue

    lightblue

  • lightcoral

    lightcoral

  • lightcyan

    lightcyan

  • lightgoldenrodyellow

    lightgoldenrodyellow

  • lightgray

    lightgray

  • lightgreen

    lightgreen

  • lightgrey

    lightgrey

  • lightpink

    lightpink

  • lightsalmon

    lightsalmon

  • lightseagreen

    lightseagreen

  • lightskyblue

    lightskyblue

  • lightslategray

    lightslategray

  • lightslategrey

    lightslategrey

  • lightsteelblue

    lightsteelblue

  • lightyellow

    lightyellow

  • lime

    lime

  • limegreen

    limegreen

  • linen

    linen

  • magenta

    magenta

  • maroon

    maroon

  • mediumaquamarine

    mediumaquamarine

  • mediumblue

    mediumblue

  • mediumorchid

    mediumorchid

  • mediumpurple

    mediumpurple

  • mediumseagreen

    mediumseagreen

  • mediumslateblue

    mediumslateblue

  • mediumspringgreen

    mediumspringgreen

  • mediumturquoise

    mediumturquoise

  • mediumvioletred

    mediumvioletred

  • midnightblue

    midnightblue

  • mintcream

    mintcream

  • mistyrose

    mistyrose

  • moccasin

    moccasin

  • navajowhite

    navajowhite

  • navy

    navy

  • oldlace

    oldlace

  • olive

    olive

  • olivedrab

    olivedrab

  • orange

    orange

  • orangered

    orangered

  • orchid

    orchid

  • palegoldenrod

    palegoldenrod

  • palegreen

    palegreen

  • paleturquoise

    paleturquoise

  • palevioletred

    palevioletred

  • papayawhip

    papayawhip

  • peachpuff

    peachpuff

  • peru

    peru

  • pink

    pink

  • plum

    plum

  • powderblue

    powderblue

  • purple

    purple

  • rebeccapurple

    rebeccapurple

  • red

    red

  • rosybrown

    rosybrown

  • royalblue

    royalblue

  • saddlebrown

    saddlebrown

  • salmon

    salmon

  • sandybrown

    sandybrown

  • seagreen

    seagreen

  • seashell

    seashell

  • sienna

    sienna

  • silver

    silver

  • skyblue

    skyblue

  • slateblue

    slateblue

  • slategray

    slategray

  • slategrey

    slategrey

  • snow

    snow

  • springgreen

    springgreen

  • steelblue

    steelblue

  • tan

    tan

  • teal

    teal

  • thistle

    thistle

  • tomato

    tomato

  • turquoise

    turquoise

  • violet

    violet

  • wheat

    wheat

  • white

    white

  • whitesmoke

    whitesmoke

  • yellow

    yellow

  • yellowgreen

    yellowgreen

plus tranparent, and currentColor which points to the color property, for example it’s useful to make the border-color inherit it.

加上tranparentcurrentColor ,它指向color属性,例如,使border-color继承它很有用。

They are defined in the . They are case insensitive.

它们在中定义。 它们不区分大小写。

Wikipedia has a which lets you pick the perfect color by its name.

Wikipedia有一个 ,您可以通过它的名称选择理想的颜色。

Named colors are not the only option.

命名的颜色不是唯一的选择。

RGB和RGBa (RGB and RGBa)

You can use the rgb() function to calculate a color from its RGB notation, which sets the color based on its red-green-blue parts. From 0 to 255:

您可以使用rgb()函数根据其RGB表示法计算颜色,该RGB表示法根据其红绿蓝部分设置颜色。 从0到255:

p {  color: rgb(255, 255, 255); /* white */    background-color: rgb(0, 0, 0); /* black */}

rgba() lets you add the alpha channel to enter a transparent part. That can be a number from 0 to 1:

rgba()允许您添加Alpha通道以输入透明零件。 可以是0到1之间的数字:

p {    background-color: rgb(0, 0, 0, 0.5);}

十六进制表示法 (Hexadecimal notation)

Another option is to express the RGB parts of the colors in the hexadecimal notation, which is composed by 3 blocks.

另一种选择是以十六进制表示法表示颜色的RGB部分,该十六进制表示法由3个块组成。

Black, which is rgb(0,0,0) is expressed as #000000 or #000 (we can shortcut the 2 numbers to 1 if they are equal).

黑色,即rgb(0,0,0)表示为#000000#000 (如果相等,我们可以将2个数字缩短为1)。

White, rgb(255,255,255) can be expressed as #ffffff or #fff.

白色rgb(255,255,255)可以表示为#ffffff#fff

The hexadecimal notation lets us express a number from 0 to 255 in just 2 digits, since they can go from 0 to “15” (f).

十六进制表示法使我们可以用2位数字表示从0到255的数字,因为它们可以从0到15(f)。

We can add the alpha channel by adding 1 or 2 more digits at the end, for example #00000033. Not all browsers support the shortened notation, so use all 6 digits to express the RGB part.

我们可以通过在末尾再添加1或2个数字来添加alpha通道,例如#00000033 。 并非所有浏览器都支持缩写符号,因此请使用所有6位数字表示RGB部分。

HSL和HSLa (HSL and HSLa)

This is a more recent addition to CSS.

这是CSS的最新版本。

HSL = Hue Saturation Lightness.

HSL =色相饱和度亮度。

In this notation, black is hsl(0, 0%, 0%) and white is hsl(0, 0%, 100%).

在这种表示法中,黑色是hsl(0, 0%, 0%) ,白色是hsl(0, 0%, 100%)

If you are more familiar with HSL than RGB because of your past knowledge, you can definitely use that.

如果您由于过去的知识而对HSL的熟悉程度超过了RGB,那么您可以肯定地使用它。

You also have hsla() which adds the alpha channel to the mix, again a number from 0 to 1: hsl(0, 0%, 0%, 0.5)

您还可以使用hsla()将Alpha通道添加到混音中,它也是从0到1的数字: hsl(0, 0%, 0%, 0.5)

单位 (UNITS)

One of the things you’ll use every day in CSS are units. They are used to set lengths, paddings, margins, align elements and so on.

每天在CSS中使用的一件事是单位。 它们用于设置长度,填充,边距,对齐元素等。

Things like px, em, rem, or percentages.

pxemremrem之类的东西。

They are everywhere. There are some obscure ones, too. We’ll go through each of them in this section.

他们无处不在。 也有一些晦涩的地方。 在本节中,我们将逐一介绍它们。

像素 (Pixels)

The most widely used measurement unit. A pixel does not actually correlate to a physical pixel on your screen, as that varies, a lot, by device (think high-DPI devices vs non-retina devices).

使用最广泛的测量单位。 像素实际上与屏幕上的物理像素不相关,因为设备之间的差异很大(请考虑高DPI设备与非视网膜设备)。

There is a convention that make this unit work consistently across devices.

有一个约定可使本机在设备之间一致地工作。

百分比 (Percentages)

Another very useful measure, percentages let you specify values in percentages of that parent element’s corresponding property.

另一个非常有用的度量,百分比使您可以指定该父元素的相应属性的百分比值。

Example:

例:

.parent {  width: 400px;}.child {  width: 50%; /* = 200px */}

实际测量单位 (Real-world measurement units)

We have those measurement units which are translated from the outside world. Mostly useless on screen, they can be useful for print stylesheets. They are:

我们拥有从外界翻译而来的度量单位。 它们通常在屏幕上无用,对于打印样式表很有用。 他们是:

  • cm a centimeter (maps to 37.8 pixels)

    cm厘米(映射到37.8像素)

  • mm a millimeter (0.1cm)

    mm一毫米(0.1厘米)

  • q a quarter of a millimeter

    q四分之一毫米

  • in an inch (maps to 96 pixels)

    in一英寸(映射到96个像素)

  • pt a point (1 inch = 72 points)

    pt的点(1英寸= 72点)

  • pc a pica (1 pica = 12 points)

    pc pica(1 pica = 12积分)

相对单位 (Relative units)

  • em is the value assigned to that element's font-size, therefore its exact value changes between elements. It does not change depending on the font used, just on the font size. In typography this measures the width of the m letter.

    em是分配给该元素的font-size值,因此其确切值在元素之间变化。 它不会根据所使用的字体而变化,而仅取决于字体大小。 在排版中,这将测量m字母的宽度。

  • rem is similar to em, but instead of varying on the current element font size, it uses the root element (html) font size. You set that font size once, and rem will be a consistent measure across all the page.

    remem相似,但是它使用根元素( html )字体大小,而不是改变当前元素的字体大小。 您只需设置一次该字体大小,即可在所有页面上一致地使用rem

  • ex is like em, but inserted of measuring the width of m, it measures the height of the x letter. It can change depending on the font used, and on the font size.

    ex类似于em ,但是插入了测量m的宽度,它测量x字母的高度。 它可以根据所使用的字体和字体大小而变化。

  • ch is like ex but instead of measuring the height of x it measures the width of 0 (zero).

    chex一样,但是不是测量x的高度,而是测量0 (零)的宽度。

视口单位 (Viewport units)

  • vw the viewport width unit represents a percentage of the viewport width. 50vw means 50% of the viewport width.

    vw 视口宽度单位代表视口宽度的百分比。 50vw表示视口宽度的50%。

  • vh the viewport height unit represents a percentage of the viewport height. 50vh means 50% of the viewport height.

    vh 视口高度单位代表视口高度的百分比。 50vh表示视口高度的50%。

  • vmin the viewport minimum unit represents the minimum between the height or width in terms of percentage. 30vmin is the 30% of the current width or height, depending which one is smaller

    vmin 视口最小单位表示以百分比表示的高度或宽度之间的最小值。 30vmin是当前宽度或高度的30%,具体取决于哪一个较小

  • vmax the viewport maximum unit represents the maximum between the height or width in terms of percentage. 30vmax is the 30% of the current width or height, depending which one is bigger

    vmax 视口最大单位表示百分比之间的高度或宽度之间的最大值。 30vmax是当前宽度或高度的30%,取决于哪一个更大

分数单位 (Fraction units)

fr are fraction units, and they are used in CSS Grid to divide space into fractions.

fr是分数单位,它们在CSS Grid中用于将空间划分为分数。

We’ll talk about them in the context of CSS Grid later on.

稍后我们将在CSS Grid的上下文中讨论它们。

网址 (URL)

When we talk about background images, @import, and more, we use the url() function to load a resource:

当我们谈论背景图像,@ @import等时,我们使用url()函数加载资源:

div {  background-image: url(test.png);}

In this case I used a relative URL, which searches the file in the folder where the CSS file is defined.

在这种情况下,我使用了一个相对URL,它在定义CSS文件的文件夹中搜索文件。

I could go one level back

我可以再上一层

div {  background-image: url(../test.png);}

or go into a folder

或进入文件夹

div {  background-image: url(subfolder/test.png);}

Or I could load a file starting from the root of the domain where the CSS is hosted:

或者,我可以从托管CSS的域的根目录开始加载文件:

div {  background-image: url(/test.png);}

Or I could use an absolute URL to load an external resource:

或者,我可以使用绝对URL加载外部资源:

div {  background-image: url(https://mysite.com/test.png);}

计算中心 (CALC)

The calc() function lets you perform basic math operations on values, and it's especially useful when you need to add or subtract a length value from a percentage.

calc()函数可让您对值执行基本的数学运算,当您需要从百分比中添加或减去长度值时,该功能特别有用。

This is how it works:

它是这样工作的:

div {    max-width: calc(80% - 100px)}

It returns a length value, so it can be used anywhere you expect a pixel value.

它返回一个长度值,因此可以在期望像素值的任何地方使用。

You can perform

你可以表演

  • additions using +

    使用+加法

  • subtractions using -

    使用-减去

  • multiplication using *

    *相乘

  • division using /

    除法使用/

One caveat: with addition and subtraction, the space around the operator is mandatory, otherwise it does not work as expected.

一个警告:加减法运算符周围的空间是强制性的,否则将无法正常工作。

Examples:

例子:

div {    max-width: calc(50% / 3)}div {    max-width: calc(50% + 3px)}

背景资料 (BACKGROUNDS)

The background of an element can be changed using several CSS properties:

可以使用几个CSS属性来更改元素的背景:

  • background-color

    background-color

  • background-image

    background-image

  • background-clip

    background-clip

  • background-position

    background-position

  • background-origin

    background-origin

  • background-repeat

    background-repeat

  • background-attachment

    background-attachment

  • background-size

    background-size

and the shorthand property background, which allows us to shorten definitions and group them on a single line.

以及简写属性background ,它使我们能够缩短定义并将它们分组在一行中。

background-color accepts a color value, which can be one of the color keywords, or an rgb or hsl value:

background-color接受一个颜色值,该值可以是color关键字之一,也可以是rgbhsl值:

p {  background-color: yellow;}div {  background-color: #333;}

Instead of using a color, you can use an image as background to an element, by specifying the image location URL:

通过指定图像位置URL,可以将图像用作元素的背景,而不是使用颜色:

div {  background-image: url(image.png);}

background-clip lets you determine the area used by the background image, or color. The default value is border-box, which extends up to the border outer edge.

background-clip使您可以确定背景图像或颜色使用的区域。 默认值为border-box ,它一直延伸到边框的外边缘。

Other values are

其他值是

  • padding-box to extend the background up to the padding edge, without the border

    padding-box将背景延伸到填充边缘,没有边框

  • content-box to extend the background up to the content edge, without the padding

    content-box可将背景扩展到内容边缘,而无需填充

  • inherit to apply the value of the parent

    inherit以应用父项的值

When using an image as background you will want to set the position of the image placement using the background-position property: left, right, center are all valid values for the X axis, and top, bottom for the Y axis:

当使用图像作为背景时,您将需要使用background-position属性设置图像放置background-positionleftrightcenter都是X轴的有效值,而topbottom是Y轴的有效值:

div {  background-position: top right;}

If the image is smaller than the background, you need to set the behavior using background-repeat. Should it repeat-x, repeat-y or repeat on all the axes? This last one is the default value. Another value is no-repeat.

如果图像小于背景,则需要使用background-repeat设置行为。 它应该在所有轴上repeat-xrepeat-y还是repeat ? 最后一个是默认值。 另一个价值是no-repeat

background-origin lets you choose where the background should be applied: to the entire element including padding (default) using padding-box, to the entire element including the border using border-box, to the element without the padding using content-box.

background-origin允许您选择应用背景的位置:使用padding-box到包括填充的整个元素(默认),使用border-box到包括边框的整个元素,使用content-box到没有填充的元素。

With background-attachment we can attach the background to the viewport, so that scrolling will not affect the background:

使用background-attachment我们可以将背景附加到视口,因此滚动不会影响背景:

div {  background-attachment: fixed;}

By default the value is scroll. There is another value, local. The best way to visualize their behavior is .

默认情况下,值是scroll 。 还有另一个值local 。 可视化其行为的最佳方法是 。

The last background property is background-size. We can use 3 keywords: auto, cover and contain. auto is the default.

最后一个背景属性是background-size 。 我们可以使用3个关键字: autocovercontainauto是默认设置。

cover expands the image until the entire element is covered by the background.

cover扩展图像,直到整个元素被背景覆盖。

contain stops expanding the background image when one dimension (x or y) covers the whole smallest edge of the image, so it's fully contained into the element.

当一个维度(x或y)覆盖图像的整个最小边缘时, contain停止扩展背景图像,因此将其完全包含在元素中。

You can also specify a length value, and if so it sets the width of the background image (and the height is automatically defined):

您还可以指定一个长度值,如果这样,它将设置背景图像的宽度(并且高度是自动定义的):

div {  background-size: 100%;}

If you specify 2 values, one is the width and the second is the height:

如果指定2个值,则一个为宽度,第二个为高度:

div {  background-size: 800px 600px;}

The shorthand property background allows to shorten definitions and group them on a single line.

速记属性background允许缩短定义并将它们分组在一行上。

This is an example:

这是一个例子:

div {  background: url(bg.png) top left no-repeat;}

If you use an image, and the image could not be loaded, you can set a fallback color:

如果使用图像,但无法加载图像,则可以设置后备颜色:

div {  background: url(image.png) yellow;}

You can also set a gradient as background:

您还可以将渐变设置为背景:

div {  background: linear-gradient(#fff, #333);}

注释 (COMMENTS)

CSS gives you the ability to write comments in a CSS file, or in the style tag in the page header

CSS使您能够在CSS文件或页面标题中的style标签中编写注释

The format is the /* this is a comment */ C-style (or JavaScript-style, if you prefer) comments.

格式是/* this is a comment */ C样式(或JavaScript样式,如果您愿意的话)注释。

This is a multiline comment. Until you add the closing */ token, the all the lines found after the opening one are commented.

这是多行注释。 在添加结束标记*/ ,将对在开始标记之后找到的所有行进行注释。

Example:

例:

#name { display: block; } /* Nice rule! *//* #name { display: block; } */#name {    display: block; /*    color: red;    */}

CSS does not have inline comments, like // in C or JavaScript.

CSS没有内联注释,例如C或JavaScript中的//

Pay attention though — if you add // before a rule, the rule will not be applied, looking like the comment worked. In reality, CSS detected a syntax error and due to how it works it ignored the line with the error, and went straight to the next line.

但是请注意-如果在规则之前添加// ,则该规则将不会应用,就像注释起作用一样。 实际上,CSS检测到语法错误,由于它的工作方式,它忽略了出现错误的行,并直接进入下一行。

Knowing this approach lets you purposefully write inline comments, although you have to be careful because you can’t add random text like you can in a block comment.

知道这种方法后,您可以有目的地编写内联注释,尽管您必须小心,因为您不能像在块注释中那样添加随机文本。

For example:

例如:

// Nice rule!#name { display: block; }

In this case, due to how CSS works, the #name rule is actually commented out. You can find more details if you find this interesting. To avoid shooting yourself in the foot, just avoid using inline comments and rely on block comments.

在这种情况下,由于CSS的工作方式,实际上会注释掉#name规则。 如果您对此感兴趣,可以找到更多详细信息。 为了避免脚步被枪杀,只需避免使用内联注释并依靠块注释。

定制属性 (CUSTOM PROPERTIES)

In the last few years CSS preprocessors have had a lot of success. It was very common for greenfield projects to start with Less or Sass. And it’s still a very popular technology.

在过去的几年中,CSS预处理器取得了很大的成功。 新建项目从Less或Sass开始是很常见的。 而且它仍然是一种非常流行的技术。

The main benefits of those technologies are, in my opinion:

我认为这些技术的主要优点是:

  • They allow you to nest selectors

    它们允许您嵌套选择器
  • The provide an easy imports functionality

    提供简单的导入功能
  • They give you variables

    他们给你变量

Modern CSS has a new powerful feature called CSS Custom Properties, also commonly known as CSS Variables.

现代CSS具有一个称为CSS自定义属性的新强大功能,通常也称为CSS变量

CSS is not a programming language like , Python, PHP, Ruby or Go where variables are key to do something useful. CSS is very limited in what it can do, and it’s mainly a declarative syntax to tell browsers how they should display an HTML page.

CSS不是像 ,Python,PHP,Ruby或Go这样的编程语言,其中变量是执行有用操作的关键。 CSS的功能非常有限,它主要是一种声明性语法,用于告诉浏览器如何显示HTML页面。

But a variable is a variable: a name that refers to a value, and variables in CSS help reduce repetition and inconsistencies in your CSS, by centralizing the values definition.

但是变量是变量:一个引用值的名称,CSS中的变量通过集中值的定义来帮助减少CSS中的重复和不一致。

And it introduces a unique feature that CSS preprocessors won’t ever have: you can access and change the value of a CSS Variable programmatically using JavaScript.

并且它引入了CSS预处理器从未有过的独特功能: 您可以使用JavaScript以编程方式访问和更改CSS变量的值

使用变量的基础 (The basics of using variables)

A CSS Variable is defined with a special syntax, prepending two dashes to a name (--variable-name), then a colon and a value. Like this:

CSS变量是使用特殊语法定义的,名称前两个破折号 ( --variable-name ),然后是冒号和值。 像这样:

:root {  --primary-color: yellow;}

(more on :root later)

(稍后更多关于:root )

You can access the variable value using var():

您可以使用var()访问变量值:

p {  color: var(--primary-color)}

The variable value can be any valid CSS value, for example:

变量值可以是任何有效CSS值,例如:

:root {  --default-padding: 30px 30px 20px 20px;  --default-color: red;  --default-background: #fff;}

在任何元素内创建变量 (Create variables inside any element)

CSS Variables can be defined inside any element. Some examples:

CSS变量可以在任何元素内定义。 一些例子:

:root {  --default-color: red;}body {  --default-color: red;}main {  --default-color: red;}p {  --default-color: red;}span {  --default-color: red;}a:hover {  --default-color: red;}

What changes in those different examples is the scope.

这些不同示例的变化是范围

变量范围 (Variables scope)

Adding variables to a selector makes them available to all the children of it.

将变量添加到选择器使它们可用于所有选择器。

In the example above you saw the use of :root when defining a CSS variable:

在上面的示例中,您看到了在定义CSS变量时使用:root情况:

:root {  --primary-color: yellow;}

:root is a CSS pseudo-class that identifies the root element of a tree.

:root是CSS伪类,用于标识树的根元素。

In the context of an HTML document, using the :root selector points to the html element, except that :root has higher specificity (takes priority).

在HTML文档的上下文中,使用:root选择器指向html元素,除了:root具有更高的特异性(优先级高)。

In the context of an SVG image, :root points to the svg tag.

在SVG映像的上下文中, :root指向svg标记。

Adding a CSS custom property to :root makes it available to all the elements in the page.

将CSS自定义属性添加到:root使其可用于页面中的所有元素。

If you add a variable inside a .container selector, it's only going to be available to children of .container:

如果在.container选择器内添加变量,则仅对.container可用:

.container {  --secondary-color: yellow;}

and using it outside of this element is not going to work.

并且在此元素之外使用它将无法正常工作。

Variables can be reassigned:

可以重新分配变量:

:root {  --primary-color: yellow;}.container {  --primary-color: blue;}

Outside .container, --primary-color will be yellow, but inside it will be blue.

.container外部,-- --primary-color将为黄色 ,但在其内部将为蓝色

You can also assign or overwrite a variable inside the HTML using inline styles:

您还可以使用内联样式在HTML中分配或覆盖变量:

CSS Variables follow the normal CSS cascading rules, with precedence set according to specificity.

CSS变量遵循正常CSS级联规则,并根据特定性设置优先级。

使用JavaScript与CSS变量值进行交互 (Interacting with a CSS Variable value using JavaScript)

The coolest thing with CSS Variables is the ability to access and edit them using JavaScript.

CSS变量最酷的地方是可以使用JavaScript访问和编辑它们。

Here’s how you set a variable value using plain JavaScript:

使用纯JavaScript设置变量值的方法如下:

const element = document.getElementById('my-element')element.style.setProperty('--variable-name', 'a-value')

This code below can be used to access a variable value instead, in case the variable is defined on :root:

如果变量是在:root上定义的,则下面的代码可用于访问变量值:

const styles = getComputedStyle(document.documentElement)const value = String(styles.getPropertyValue('--variable-name')).trim()

Or, to get the style applied to a specific element, in case of variables set with a different scope:

或者,在变量设置为不同范围的情况下,将样式应用于特定元素:

const element = document.getElementById('my-element')const styles = getComputedStyle(element)const value = String(styles.getPropertyValue('--variable-name')).trim()

处理无效值 (Handling invalid values)

If a variable is assigned to a property which does not accept the variable value, it’s considered invalid.

如果将变量分配给不接受该变量值的属性,则认为该变量无效。

For example you might pass a pixel value to a position property, or a rem value to a color property.

例如,您可以将像素值传递给position属性,或者将rem值传递给color属性。

In this case the line is considered invalid and is ignored.

在这种情况下,该行被认为是无效的,将被忽略。

浏览器支持 (Browser support)

Browser support for CSS Variables is very good, .

浏览器对CSS变量的支持非常好

CSS Variables are here to stay, and you can use them today if you don’t need to support Internet Explorer and old versions of the other browsers.

CSS变量将保留下来,如果您不需要支持Internet Explorer和其他浏览器的旧版本,则可以在今天使用它们。

If you need to support older browsers you can use libraries like or , but you’ll lose the ability to interact with variables via JavaScript or the Browser Developer Tools, as they are transpiled to good old variable-less CSS (and as such, you lose most of the power of CSS Variables).

如果您需要支持较旧的浏览器,则可以使用或类的库,但是由于将它们转换为旧的无变量CSS(例如, ,则会失去大多数CSS变量的功能)。

CSS变量区分大小写 (CSS Variables are case sensitive)

This variable:

此变量:

--width: 100px;

is different than this one:

与此不同:

--Width: 100px;

CSS变量中的数学 (Math in CSS Variables)

To do math in CSS Variables, you need to use calc(), for example:

要在CSS变量中进行数学运算,您需要使用calc() ,例如:

:root {  --default-left-padding: calc(10px * 2);}

使用CSS变量进行媒体查询 (Media queries with CSS Variables)

Nothing special here. CSS Variables normally apply to media queries:

这里没什么特别的。 CSS变量通常适用于媒体查询:

body {  --width: 500px;}@media screen and (max-width: 1000px) and (min-width: 700px) {  --width: 800px;}.container {  width: var(--width);}

为var()设置后备值 (Setting a fallback value for var())

var() accepts a second parameter, which is the default fallback value when the variable value is not set:

var()接受第二个参数,这是未设置变量值时的默认后备值:

.container {  margin: var(--default-margin, 30px);}

字体 (FONTS)

At the dawn of the web you only had a handful of fonts you could choose from.

在网络诞生之初,您只有少数几种字体可以选择。

Thankfully today you can load any kind of font on your pages.

值得庆幸的是,今天您可以在页面上加载任何字体。

CSS has gained many nice capabilities over the years in regards to fonts.

多年来,CSS在字体方面获得了许多不错的功能。

The font property is the shorthand for a number of properties:

font属性是许多属性的简写:

  • font-family

    font-family

  • font-weight

    font-weight

  • font-stretch

    font-stretch

  • font-style

    font-style

  • font-size

    font-size

Let’s see each one of them and then we’ll cover font.

让我们看看它们中的每一个,然后我们将介绍font

Then we’ll talk about how to load custom fonts, using @import or @font-face, or by loading a font stylesheet.

然后,我们将讨论如何使用@import@font-face或通过加载字体样式表来加载自定义字体。

font-family (font-family)

Sets the font family that the element will use.

设置元素将使用的字体系列

Why “family”? Because what we know as a font is actually composed of several sub-fonts which provide all the style (bold, italic, light..) we need.

为什么是“家庭”? 因为我们所知道的字体实际上是由几个子字体组成的,它们提供了我们需要的所有样式(粗体,斜体,浅色..)。

Here’s an example from my Mac’s Font Book app — the Fira Code font family hosts several dedicated fonts underneath:

这是我Mac的Font Book应用程序中的一个示例-Fira Code字体家族在下面托管了几种专用字体:

This property lets you select a specific font, for example:

此属性使您可以选择特定的字体,例如:

body {  font-family: Helvetica;}

You can set multiple values, so the second option will be used if the first cannot be used for some reason (if it’s not found on the machine, or the network connection to download the font failed, for example):

您可以设置多个值,因此,如果由于某种原因无法使用第一个选项(例如,在计算机上找不到该选项,或者下载字体的网络连接失败),则将使用第二个选项:

body {  font-family: Helvetica, Arial;}

I used some specific fonts up to now, ones we call Web Safe Fonts, as they are pre-installed on different operating systems.

到目前为止,我使用了一些特定的字体,我们将其称为Web安全字体 ,因为它们预先安装在不同的操作系统上。

We divide them in Serif, Sans-Serif, and Monospace fonts. Here’s a list of some of the most popular ones:

我们将它们分为Serif,Sans-Serif和Monospace字体。 以下是一些最受欢迎的列表:

Serif

衬线

  • Georgia

    佐治亚州
  • Palatino

    帕拉蒂诺
  • Times New Roman

    英语字体格式一种
  • Times

    时报

Sans-Serif

无衬线字体

  • Arial

    Arial
  • Helvetica

    海尔维蒂察
  • Verdana

    Verdana
  • Geneva

    日内瓦
  • Tahoma

    塔豪玛
  • Lucida Grande

    露西达·格兰德(Lucida Grande)
  • Impact

    影响力
  • Trebuchet MS

    Trebuchet MS
  • Arial Black

    艾里亚·布莱克

Monospace

等宽

  • Courier New

    快递新
  • Courier

    信使
  • Lucida Console

    Lucida控制台
  • Monaco

    摩纳哥

You can use all of those as font-family properties, but they are not guaranteed to be there for every system. Others exist, too, with a varying level of support.

您可以将所有这些都用作font-family属性,但不能保证它们在每个系统中都存在。 其他人也存在不同程度的支持。

You can also use generic names:

您也可以使用通用名称:

  • sans-serif a font without ligatures

    sans-serif没有连字的字体

  • serif a font with ligatures

    serif字体带连字

  • monospace a font especially good for code

    monospace字体,特别适合代码

  • cursive used to simulate handwritten pieces

    cursive用于模拟手写作品

  • fantasy the name says it all

    fantasy这个名字说明了一切

Those are typically used at the end of a font-family definition, to provide a fallback value in case nothing else can be applied:

这些通常用于font-family定义的末尾,以提供备用值,以防万一无法应用其他任何方法:

body {  font-family: Helvetica, Arial, sans-serif;}

font-weight (font-weight)

This property sets the width of a font. You can use those predefined values:

此属性设置字体的宽度。 您可以使用这些预定义的值:

  • normal

    正常
  • bold

    胆大
  • bolder (relative to the parent element)

    粗体(相对于父元素)
  • lighter (relative to the parent element)

    更轻(相对于父元素)

Or using the numeric keywords

或使用数字关键字

  • 100

    100
  • 200

    200
  • 300

    300
  • 400, mapped to normal

    400,映射为normal

  • 500

    500
  • 600

    600
  • 700 mapped to bold

    700映射为bold

  • 800

    800
  • 900

    900

where 100 is the lightest font, and 900 is the boldest.

其中100是最浅的字体,而900是最粗体。

Some of those numeric values might not map to a font, because that must be provided in the font family. When one is missing, CSS makes that number be at least as bold as the preceding one, so you might have numbers that point to the same font.

其中一些数字值可能不会映射到字体,因为必须在字体系列中提供该值。 如果缺少一个,CSS将使该数字至少与前一个数字一样大胆,因此您可能会有指向相同字体的数字。

font-stretch (font-stretch)

Allows you to choose a narrow or wide face of the font, if available.

允许您选择字体的窄字体或宽字体(如果可用)。

This is important: the font must be equipped with different faces.

这很重要:字体必须配备不同的字体。

Values allowed are, from narrower to wider:

允许的值从窄到宽:

  • ultra-condensed

    ultra-condensed

  • extra-condensed

    extra-condensed

  • condensed

    condensed

  • semi-condensed

    semi-condensed

  • normal

    normal

  • semi-expanded

    semi-expanded

  • expanded

    expanded

  • extra-expanded

    extra-expanded

  • ultra-expanded

    ultra-expanded

font-style (font-style)

Allows you to apply an italic style to a font:

允许您将斜体样式应用于字体:

p {  font-style: italic;}

This property also allows the values oblique and normal. There is very little, if any, difference between using italic and oblique. The first is easier to me, as HTML already offers an i element which means italic.

此属性还允许值obliquenormal 。 很少有,如果有的话,使用之间的差异italicoblique 。 第一个对我来说比较容易,因为HTML已经提供了一个i元素,它表示斜体。

font-size (font-size)

This property is used to determine the size of fonts.

此属性用于确定字体的大小。

You can pass 2 kinds of values:

您可以传递2种值:

  1. a length value, like px, em, rem etc, or a percentage

    长度值,例如pxemrem等,或百分比

  2. a predefined value keyword

    预定义的值关键字

In the second case, the values you can use are:

在第二种情况下,可以使用的值为:

  • xx-small

    xx小
  • x-small

  • small

  • medium

  • large

  • x-large

    x大
  • xx-large

    xx大
  • smaller (relative to the parent element)

    较小(相对于父元素)
  • larger (relative to the parent element)

    更大(相对于父元素)

Usage:

用法:

p {  font-size: 20px;}li {  font-size: medium;}

font-variant (font-variant)

This property was originally used to change the text to small caps, and it had just 3 valid values:

此属性最初用于将文本更改为小写,并且只有3个有效值:

  • normal

    normal

  • inherit

    inherit

  • small-caps

    small-caps

Small caps means the text is rendered in “smaller caps” beside its uppercase letters.

小写大写表示文本以大写字母旁边的“小写大写”呈现。

font (font)

The font property lets you apply different font properties in a single one, reducing the clutter.

font属性使您可以在一个字体中应用不同的字体属性,从而减少混乱。

We must at least set 2 properties, font-size and font-family, the others are optional:

我们必须至少设置2个属性, font-sizefont-family ,其他属性是可选的:

body {  font: 20px Helvetica;}

If we add other properties, they need to be put in the correct order.

如果我们添加其他属性,则需要以正确的顺序放置它们。

This is the order:

这是命令:

font: 
;

Example:

例:

body {  font: italic bold 20px Helvetica;}section {  font: small-caps bold 20px Helvetica;}

使用@font-face加载自定义字体 (Loading custom fonts using @font-face)

@font-face lets you add a new font family name, and map it to a file that holds a font.

@font-face允许您添加新的字体系列名称,并将其映射到包含字体的文件。

This font will be downloaded by the browser and used in the page, and it’s been such a fundamental change to typography on the web — we can now use any font we want.

该字体将由浏览器下载并在页面中使用,这是对网络排版的根本改变,我们现在可以使用所需的任何字体。

We can add @font-face declarations directly into our CSS, or link to a CSS dedicated to importing the font.

我们可以将@font-face声明直接添加到我们CSS中,或链接到专用于导入字体CSS。

In our CSS file we can also use @import to load that CSS file.

在我们CSS文件中,我们还可以使用@import加载该CSS文件。

A @font-face declaration contains several properties we use to define the font, including src, the URI (one or more URIs) to the font. This follows the same-origin policy, which means fonts can only be downloaded form the current origin (domain + port + protocol).

@font-face声明包含一些用于定义字体的属性,包括src ,字体的URI(一个或多个URI)。 这遵循同源策略,这意味着只能从当前源(域+端口+协议)下载字体。

Fonts are usually in the formats

字体通常采用以下格式

  • woff (Web Open Font Format)

    woff (Web开放字体格式)

  • woff2 (Web Open Font Format 2.0)

    woff2 (网络开放字体格式2.0)

  • eot (Embedded Open Type)

    eot (嵌入式开放式)

  • otf (OpenType Font)

    otf (OpenType字体)

  • ttf (TrueType Font)

    ttf (TrueType字体)

The following properties allow us to define the properties to the font we are going to load, as we saw above:

如下所示,以下属性使我们能够定义将要加载的字体的属性:

  • font-family

    font-family

  • font-weight

    font-weight

  • font-style

    font-style

  • font-stretch

    font-stretch

性能说明 (A note on performance)

Of course loading a font has performance implications which you must consider when creating the design of your page.

当然,加载字体会影响性能,在创建页面设计时必须考虑这些影响。

印刷术 (TYPOGRAPHY)

We already talked about fonts, but there’s more to styling text.

我们已经讨论过字体,但是样式样式还有更多。

In this section we’ll talk about the following properties:

在本节中,我们将讨论以下属性:

  • text-transform

    text-transform

  • text-decoration

    text-decoration

  • text-align

    text-align

  • vertical-align

    vertical-align

  • line-height

    line-height

  • text-indent

    text-indent

  • text-align-last

    text-align-last

  • word-spacing

    word-spacing

  • letter-spacing

    letter-spacing

  • text-shadow

    text-shadow

  • white-space

    white-space

  • tab-size

    tab-size

  • writing-mode

    writing-mode

  • hyphens

    hyphens

  • text-orientation

    text-orientation

  • direction

    direction

  • line-break

    line-break

  • word-break

    word-break

  • overflow-wrap

    overflow-wrap

text-transform (text-transform)

This property can transform the case of an element.

此属性可以转换元素的大小写。

There are 4 valid values:

有4个有效值:

  • capitalize to uppercase the first letter of each word

    capitalize为大写每个单词的第一个字母

  • uppercase to uppercase all the text

    uppercase写到全部大写

  • lowercase to lowercase all the text

    lowercase将所有文本都小写

  • none to disable transforming the text, used to avoid inheriting the property

    none禁用转换文本,用于避免继承属性

Example:

例:

p {  text-transform: uppercase;}

text-decoration (text-decoration)

This property is sed to add decorations to the text, including

设置此属性可为文本添加装饰,包括

  • underline

    underline

  • overline

    overline

  • line-through

    line-through

  • blink

    blink

  • none

    none

Example:

例:

p {  text-decoration: underline;}

You can also set the style of the decoration, and the color.

您还可以设置装饰的样式和颜色。

Example:

例:

p {  text-decoration: underline dashed yellow;}

Valid style values are solid, double, dotted, dashed, wavy.

有效的样式值是soliddouble dotteddasheddashedwavy

You can do all in one line, or use the specific properties:

您可以全部完成一行操作,也可以使用特定的属性:

  • text-decoration-line

    text-decoration-line

  • text-decoration-color

    text-decoration-color

  • text-decoration-style

    text-decoration-style

Example:

例:

p {  text-decoration-line: underline;  text-decoration-color: yellow;  text-decoration-style: dashed;}

text-align (text-align)

By default text align has the start value, meaning the text starts at the "start", origin 0, 0 of the box that contains it. This means top left in left-to-right languages, and top right in right-to-left languages.

默认情况下,文本对齐有start值,在“开始”,原点0,包含它的箱子0意味着该文本开始。 这意味着左上用左到右的语言,右上用右到左的语言。

Possible values are start, end, left, right, center, justify (nice to have a consistent spacing at the line ends):

可能的值是startendleftrightcenterjustify (很好的在行尾具有一致的间距):

p {  text-align: right;}

vertical-align (vertical-align)

Determines how inline elements are vertically aligned.

确定嵌入式元素如何垂直对齐。

We have several values for this property. First we can assign a length or percentage value. Those are used to align the text in a position higher or lower (using negative values) than the baseline of the parent element.

我们为此属性提供了多个值。 首先,我们可以指定一个长度或百分比值。 这些用于将文本对齐到比父元素的基线更高或更低的位置(使用负值)。

Then we have the keywords:

然后,我们有了关键字:

  • baseline (the default), aligns the baseline to the baseline of the parent element

    baseline (默认),将基线与父元素的基线对齐

  • sub makes an element subscripted, simulating the sub HTML element result

    sub使元素下标,模拟sub HTML元素结果

  • super makes an element superscripted, simulating the sup HTML element result

    super使元素上标,模拟sup HTML元素结果

  • top align the top of the element to the top of the line

    top将元素的顶部与行的top对齐

  • text-top align the top of the element to the top of the parent element font

    text-top将元素的顶部与父元素的字体text-top对齐

  • middle align the middle of the element to the middle of the line of the parent

    将元素的middle对齐到父级行的中间

  • bottom align the bottom of the element to the bottom of the line

    使元素的底部与行的bottom对齐

  • text-bottom align the bottom of the element to the bottom of the parent element font

    text-bottom将元素的底部与父元素字体text-bottom对齐

line-height (line-height)

This allows you to change the height of a line. Each line of text has a certain font height, but then there is additional spacing vertically between the lines. That’s the line height:

这使您可以更改线条的高度。 每一行文本都有一定的字体高度,但是行之间在垂直方向上还有额外的间距。 那是行高:

p {  line-height: 0.9rem;}

text-indent (text-indent)

Indent the first line of a paragraph by a set length, or a percentage of the paragraph width:

将段落的第一行缩进设定的长度或段落宽度的百分比:

p {  text-indent: -10px;}

text-align-last (text-align-last)

By default the last line of a paragraph is aligned following the text-align value. Use this property to change that behavior:

默认情况下,段落的最后一行在text-align值之后text-align 。 使用此属性可以更改该行为:

p {  text-align-last: right;}

word-spacing (word-spacing)

Modifies the spacing between each word.

修改每个单词之间的间距。

You can use the normal keyword, to reset inherited values, or use a length value:

您可以使用normal关键字来重置继承的值,也可以使用长度值:

p {  word-spacing: 2px;}span {  word-spacing: -0.2em;}

letter-spacing (letter-spacing)

Modifies the spacing between each letter.

修改每个字母之间的间距。

You can use the normal keyword, to reset inherited values, or use a length value:

您可以使用normal关键字来重置继承的值,也可以使用长度值:

p {  letter-spacing: 0.2px;}span {  letter-spacing: -0.2em;}

text-shadow (text-shadow)

Apply a shadow to the text. By default the text has now shadow.

在文字上加上阴影。 默认情况下,文本现在带有阴影。

This property accepts an optional color, and a set of values that set

此属性接受可选的颜色以及一组设置的值

  • the X offset of the shadow from the text

    阴影从文本的X偏移量
  • the Y offset of the shadow from the text

    阴影从文本的Y偏移
  • the blur radius

    模糊半径

If the color is not specified, the shadow will use the text color.

如果未指定颜色,则阴影将使用文本颜色。

Examples:

例子:

p {  text-shadow: 0.2px 2px;}span {  text-shadow: yellow 0.2px 2px 3px;}

white-space (white-space)

Sets how CSS handles the white space, new lines and tabs inside an element.

设置CSS如何处理元素内的空白,换行和制表符。

Valid values that collapse white space are:

折叠空白的有效值为:

  • normal collapses white space. Adds new lines when necessary as the text reaches the container end

    normal折叠空白。 当文本到达容器末端时,在必要时添加新行

  • nowrap collapses white space. Does not add a new line when the text reaches the end of the container, and suppresses any line break added to the text

    nowrap折叠空白区域。 当文本到达容器的末尾时不添加新行,并禁止添加到文本的任何换行符

  • pre-line collapses white space. Adds new lines when necessary as the text reaches the container end

    pre-line折叠空白。 当文本到达容器末端时,在必要时添加新行

Valid values that preserve white space are:

保留空白的有效值为:

  • pre preserves white space. Does not add a new line when the text reaches the end of the container, but preserves line break added to the text

    pre保留空白。 当文本到达容器的末尾时不添加新行,但保留添加到文本的换行符

  • pre-wrap preserves white space. Adds new lines when necessary as the text reaches the container end

    pre-wrap保留空白。 当文本到达容器末端时,在必要时添加新行

tab-size (tab-size)

Sets the width of the tab character. By default it’s 8, and you can set an integer value that sets the character spaces it takes, or a length value:

设置制表符的宽度。 默认情况下为8,您可以设置一个整数值来设置它占用的字符空间,或者一个长度值:

p {  tab-size: 2;}span {  tab-size: 4px;}

writing-mode (writing-mode)

Defines whether lines of text are laid out horizontally or vertically, and the direction in which blocks progress.

定义文本行是水平放置还是垂直放置,以及块前进的方向。

The values you can use are

您可以使用的值是

  • horizontal-tb (default)

    horizontal-tb (默认)

  • vertical-rl content is laid out vertically. New lines are put on the left of the previous

    vertical-rl内容垂直放置。 新行放在上一行的左侧

  • vertical-lr content is laid out vertically. New lines are put on the right of the previous

    vertical-lr内容垂直放置。 新行放在上一行的右侧

hyphens (hyphens)

Determines if hyphens should be automatically added when going to a new line.

确定在换行时是否应自动添加连字符。

Valid values are

有效值为

  • none (default)

    none (默认)

  • manual only add an hyphen when there is already a visible hyphen or a hidden hyphen (a special character)

    manual仅在已有可见的连字符或隐藏的连字符(特殊字符)时添加连字符

  • auto add hyphens when determined the text can have a hyphen.

    确定文本可以带有连字符时, auto添加连字符。

text-orientation (text-orientation)

When writing-mode is in a vertical mode, determines the orientation of the text.

writing-mode处于垂直模式时,确定文本的方向。

Valid values are

有效值为

  • mixed is the default, and if a language is vertical (like Japanese) it preserves that orientation, while rotating text written in western languages

    默认情况下为“ mixed ”,如果语言是垂直语言(如日语),则在旋转以西方语言书写的文本时,将保持该方向

  • upright makes all text be vertically oriented

    upright使所有文本都垂直放置

  • sideways makes all text horizontally oriented

    sideways使所有文本水平定向

direction (direction)

Sets the direction of the text. Valid values are ltr and rtl:

设置文本的方向。 有效值为ltrrtl

p {  direction: rtl;}

word-break (word-break)

This property specifies how to break lines within words.

此属性指定如何在单词内换行。

  • normal (default) means the text is only broken between words, not inside a word

    normal (默认)表示文本仅在单词之间打断,而不在单词内部

  • break-all the browser can break a word (but no hyphens are added)

    break-all浏览器都可以破坏单词(但不添加连字符)

  • keep-all suppress soft wrapping. Mostly used for CJK (Chinese/Japanese/Korean) text.

    keep-all压软包装。 主要用于CJK(中文/日文/韩文)文本。

Speaking of CJK text, the property line-break is used to determine how text lines break. I'm not an expert with those languages, so I will avoid covering it.

说到CJK文本,属性line-break用于确定文本行的断开方式。 我不是那些语言的专家,所以我会避免涉及它。

overflow-wrap (overflow-wrap)

If a word is too long to fit a line, it can overflow outside of the container.

如果单词太长而无法容纳一行,它可能会在容器外部溢出。

This property is also known as word-wrap, although that is non-standard (but still works as an alias)

此属性也称为word-wrap ,尽管这是非标准的(但仍可以用作别名)

This is the default behavior (overflow-wrap: normal;).

这是默认行为( overflow-wrap: normal; )。

We can use:

我们可以用:

p {  overflow-wrap: break-word;}

to break it at the exact length of the line, or

在行的确切长度处将其断开,或者

p {  overflow-wrap: anywhere;}

if the browser sees there’s a soft wrap opportunity somewhere earlier. No hyphens are added, in any case.

如果浏览器发现较早的某个地方存在软包装的机会。 在任何情况下都不会添加连字符。

This property is very similar to word-break. We might want to choose this one on western languages, while word-break has special treatment for non-western languages.

此属性与word-break非常相似。 我们可能想在西方语言中选择一种,而word-break对非西方语言有特殊的对待。

箱型 (BOX MODEL)

Every CSS element is essentially a box. Every element is a generic box.

每个CSS元素本质上都是一个盒子。 每个元素都是一个通用框。

The box model explains the sizing of the elements based on a few CSS properties.

盒子模型基于一些CSS属性说明了元素的大小。

From the inside to the outside, we have:

从内部到外部,我们有:

  • the content area

    内容区
  • padding

    填充
  • border

    边境
  • margin

    保证金

The best way to visualize the box model is to open the browser DevTools and check how it is displayed:

可视化盒子模型的最佳方法是打开浏览器DevTools并检查其显示方式:

Here you can see how Firefox tells me the properties of a span element I highlighted. I right-clicked on it, pressed Inspect Element, and went to the Layout panel of the DevTools.

在这里,您可以看到Firefox如何告诉我突出显示的span元素的属性。 我右键单击它,按Inspect Element,然后转到DevTools的“布局”面板。

See, the light blue space is the content area. Surrounding it there is the padding, then the border and finally the margin.

看到,浅蓝色空间是内容区域。 围绕它的是填充,然后是边框,最后是边距。

By default, if you set a width (or height) on the element, that is going to be applied to the content area. All the padding, border, and margin calculations are done outside of the value, so you have to keep this in mind when you do your calculation.

默认情况下,如果您在元素上设置宽度(或高度),则该宽度(或高度)将应用于内容区域 。 所有的填充,边界和边距计算都在值之外进行,因此在进行计算时必须牢记这一点。

Later you’ll see how you can change this behavior using Box Sizing.

稍后,您将看到如何使用Box Sizing更改此行为。

边境 (BORDER)

The border is a thin layer between padding and margin. By editing the border, you can make elements draw their perimeter on screen.

边框是填充和边距之间的薄层。 通过编辑边框,可以使元素在屏幕上绘制其边界。

You can work on borders by using those properties:

您可以使用以下属性来处理边框:

  • border-style

    border-style

  • border-color

    border-color

  • border-width

    border-width

The property border can be used as a shorthand for all those properties.

属性border可以用作所有这些属性的简写。

border-radius is used to create rounded corners.

border-radius用于创建圆角。

You also have the ability to use images as borders, an ability given to you by border-image and its specific separate properties:

您还可以将图像用作边框, border-image及其特定的单独属性赋予您以下功能:

  • border-image-source

    border-image-source

  • border-image-slice

    border-image-slice

  • border-image-width

    border-image-width

  • border-image-outset

    border-image-outset

  • border-image-repeat

    border-image-repeat

Let’s start with border-style.

让我们从border-style开始。

边框样式 (The border style)

The border-style property lets you choose the style of the border. The options you can use are:

border-style属性使您可以选择border-style 。 您可以使用的选项是:

  • dotted

    dotted

  • dashed

    dashed

  • solid

    solid

  • double

    double

  • groove

    groove

  • ridge

    ridge

  • inset

    inset

  • outset

    outset

  • none

    none

  • hidden

    hidden

Check out for a live example.

查看的实时示例。

The default for the style is none, so to make the border appear at all you need to change it to something else. solid is a good choice most of the time.

样式的默认值为none ,因此要使边框完全显示,您需要将其更改为其他样式。 大多数情况下, solid是一个不错的选择。

You can set a different style for each edge using the properties

您可以使用属性为每个边缘设置不同的样式

  • border-top-style

    border-top-style

  • border-right-style

    border-right-style

  • border-bottom-style

    border-bottom-style

  • border-left-style

    border-left-style

or you can use border-style with multiple values to define them, using the usual Top-Right-Bottom-Left order:

或者您可以使用带有多个值的border-style来定义它们,使用通常的Top-Right-Bottom-Left顺序:

p {  border-style: solid dotted solid dotted;}

边框宽度 (The border width)

border-width is used to set the width of the border.

border-width用于设置border-width

You can use one of the pre-defined values:

您可以使用以下预定义的值之一:

  • thin

    thin

  • medium (the default value)

    medium (默认值)

  • thick

    thick

or express a value in pixels, em or rem or any other valid length value.

或以像素,em或rem表示的值或任何其他有效长度值。

Example:

例:

p {  border-width: 2px;}

You can set the width of each edge (Top-Right-Bottom-Left) separately by using 4 values:

您可以使用4个值分别设置每个边缘的宽度(上下左右):

p {  border-width: 2px 1px 2px 1px;}

or you can use the specific edge properties border-top-width, border-right-width, border-bottom-width, border-left-width.

或者,您可以使用特定的边缘属性border-top-widthborder-right-widthborder-bottom-widthborder-left-width

边框颜色 (The border color)

border-color is used to set the color of the border.

border-color用于设置border-color

If you don’t set a color, the border by default is colored using the color of the text in the element.

如果未设置颜色,则默认情况下将使用元素中文本的颜色为边框着色。

You can pass any valid color value to border-color.

您可以将任何有效的颜色值传递给border-color

Example:

例:

p {  border-color: yellow;}

You can set the color of each edge (Top-Right-Bottom-Left) separately by using 4 values:

您可以使用4个值分别设置每个边缘的颜色(上-右-下-左):

p {  border-color: black red yellow blue;}

or you can use the specific edge properties border-top-color, border-right-color, border-bottom-color, border-left-color.

或者,您可以使用特定的边缘属性border-top-colorborder-right-colorborder-bottom-colorborder-left-color

边境简写属性 (The border shorthand property)

Those 3 properties mentioned, border-width, border-style and border-color can be set using the shorthand property border.

可以使用速记属性border设置提到的这3个属性border-widthborder-styleborder-color

Example:

例:

p {  border: 2px black solid;}

You can also use the edge-specific properties border-top, border-right, border-bottom, border-left.

您还可以使用特定于边缘的属性border-topborder-rightborder-bottomborder-left

Example:

例:

p {  border-left: 2px black solid;  border-right: 3px red dashed;}

边界半径 (The border radius)

border-radius is used to set rounded corners to the border. You need to pass a value that will be used as the radius of the circle that will be used to round the border.

border-radius用于设置圆角到边框。 您需要传递一个值,该值将用作将边界变圆的圆的半径。

Usage:

用法:

p {  border-radius: 3px;}

You can also use the edge-specific properties border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius.

您还可以使用特定于边缘的属性border-top-left-radiusborder-top-right-radiusborder-bottom-left-radiusborder-bottom-right-radius

使用图像作为边框 (Using images as borders)

One very cool thing with borders is the ability to use images to style them. This lets you go very creative with borders.

带有边框的一件很酷的事情是使用图像对它们进行样式设置的能力。 这使您在边框方面变得很有创意。

We have 5 properties:

我们有5个属性:

  • border-image-source

    border-image-source

  • border-image-slice

    border-image-slice

  • border-image-width

    border-image-width

  • border-image-outset

    border-image-outset

  • border-image-repeat

    border-image-repeat

and the shorthand border-image. I won't go in much details here as images as borders would need a more in-depth coverage as what I can do in this little chapter. I recommend reading the for more information.

以及简写的border-image 。 我在这里不做过多介绍,因为像边框一样的图像需要更深入的介绍,就像我在本小章中所做的那样。 我建议阅读的以获取更多信息。

填充 (PADDING)

The padding CSS property is commonly used in CSS to add space in the inner side of an element.

padding CSS属性通常在CSS中使用,以在元素内侧添加空间。

Remember:

记得:

  • margin adds space outside an element border

    margin在元素边界外增加了空间

  • padding adds space inside an element border

    padding会在元素边框内添加空间

特定的填充属性 (Specific padding properties)

padding has 4 related properties that alter the padding of a single edge at once:

padding具有4个相关属性,可同时更改单个边缘的padding:

  • padding-top

    padding-top

  • padding-right

    padding-right

  • padding-bottom

    padding-bottom

  • padding-left

    padding-left

The usage of those is very simple and cannot be confused, for example:

这些的用法非常简单,不能混淆,例如:

padding-left: 30px;padding-right: 3em;

使用padding速记 (Using the padding shorthand)

padding is a shorthand to specify multiple padding values at the same time, and depending on the number of values entered, it behaves differently.

padding是同时指定多个padding值的简写,并且根据输入的值的数量,其行为会有所不同。

1个值 (1 value)

Using a single value applies that to all the paddings: top, right, bottom, left.

使用单个值会将其应用于所有填充:顶部,右侧,底部,左侧。

padding: 20px;

2个值 (2 values)

Using 2 values applies the first to bottom & top, and the second to left & right.

使用2个值将第一个应用于底部和顶部 ,将第二个应用于左侧和右侧

padding: 20px 10px;

3个值 (3 values)

Using 3 values applies the first to top, the second to left & right, the third to bottom.

使用3个值将第一个应用到顶部 ,第二个应用到左侧和右侧 ,第三个应用到底部

padding: 20px 10px 30px;

4个值 (4 values)

Using 4 values applies the first to top, the second to right, the third to bottom, the fourth to left.

使用4个值将第一个应用到顶部 ,第二个应用到右侧 ,第三个应用到底部 ,第四个应用到左侧

padding: 20px 10px 5px 0px;

So, the order is top-right-bottom-left.

因此,顺序为右上-右下-左

接受值 (Values accepted)

padding accepts values expressed in any kind of length unit, the most common ones are px, em, rem, but .

padding接受以任何一种长度单位表示的值,最常见的是px,em,rem,但 。

G (MARGIN)

The margin CSS property is commonly used in CSS to add space around an element.

margin CSS属性通常在CSS中用于在元素周围添加空间。

Remember:

记得:

  • margin adds space outside an element border

    margin在元素边界外增加了空间

  • padding adds space inside an element border

    padding在元素边框内添加空间

特定保证金属性 (Specific margin properties)

margin has 4 related properties that alter the margin of a single edge at once:

margin具有4个相关属性,可同时更改单个边的边距:

  • margin-top

    margin-top

  • margin-right

    margin-right

  • margin-bottom

    margin-bottom

  • margin-left

    margin-left

The usage of those is very simple and cannot be confused, for example:

这些的用法非常简单,不能混淆,例如:

margin-left: 30px;margin-right: 3em;

使用margin速记 (Using the margin shorthand)

margin is a shorthand to specify multiple margins at the same time, and depending on the number of values entered, it behaves differently.

margin是同时指定多个边距的简写,并且根据输入的值的数量,其行为会有所不同。

1个值 (1 value)

Using a single value applies that to all the margins: top, right, bottom, left.

使用单个值会将其应用于所有边距:上,右,下,左。

margin: 20px;

2个值 (2 values)

Using 2 values applies the first to bottom & top, and the second to left & right.

使用2个值将第一个应用于底部和顶部 ,将第二个应用于左侧和右侧

margin: 20px 10px;

3个值 (3 values)

Using 3 values applies the first to top, the second to left & right, the third to bottom.

使用3个值将第一个应用到顶部 ,第二个应用到左侧和右侧 ,第三个应用到底部

margin: 20px 10px 30px;

4个值 (4 values)

Using 4 values applies the first to top, the second to right, the third to bottom, the fourth to left.

使用4个值将第一个应用到顶部 ,第二个应用到右侧 ,第三个应用到底部 ,第四个应用到左侧

margin: 20px 10px 5px 0px;

So, the order is top-right-bottom-left.

因此,顺序为右上-右下-左

接受值 (Values accepted)

margin accepts values expressed in any kind of length unit, the most common ones are px, em, rem, but .

margin接受以任何一种长度单位表示的值,最常见的是px,em,rem,但 。

It also accepts percentage values, and the special value auto.

它还接受百分比值和特殊值auto

使用auto将元素居中 (Using auto to center elements)

auto can be used to tell the browser to select automatically a margin, and it's most commonly used to center an element in this way:

auto可以用于告诉浏览器自动选择边距,并且最常用于以这种方式居中元素:

margin: 0 auto;

As said above, using 2 values applies the first to bottom & top, and the second to left & right.

如上所述,使用2个值将第一个应用于bottom和top ,将第二个应用于left&right

The modern way to center elements is to use , and its justify-content: center; directive.

元素居中的现代方法是使用 ,其justify-content: center; 指示。

Older browsers of course do not implement Flexbox, and if you need to support them margin: 0 auto; is still a good choice.

较旧的浏览器当然不会实现Flexbox,并且如果您需要支持它们, margin: 0 auto; 仍然是一个不错的选择。

使用负边距 (Using a negative margin)

margin is the only property related to sizing that can have a negative value. It's extremely useful, too. Setting a negative top margin makes an element move over elements before it, and given enough negative value it will move out of the page.

margin是唯一与尺寸相关的属性,可以具有负值。 这也非常有用。 设置负的上边距会使元素在其之前的元素上移动,并且给定足够的负值,它将移出页面。

A negative bottom margin moves up the elements after it.

负底边距在其后向上移动元素。

A negative right margin makes the content of the element expand beyond its allowed content size.

负的页边空白会使元素的内容扩展到其允许的内容大小之外。

A negative left margin moves the element left over the elements that precede it, and given enough negative value it will move out of the page.

负的左边距将元素移到其前一个元素的上方,并且给定足够的负值,它将移出页面。

包装尺寸 (BOX SIZING)

The default behavior of browsers when calculating the width of an element is to apply the calculated width and height to the content area, without taking any of the padding, border and margin in consideration.

浏览器在计算元素宽度时的默认行为是将计算出的宽度和高度应用于内容区域 ,而不考虑任何填充,边框和边距。

This approach has proven to be quite complicated to work with.

实践证明,这种方法非常复杂。

You can change this behavior by setting the box-sizing property.

您可以通过设置box-sizing属性来更改此行为。

The box-sizing property is a great help. It has 2 values:

box-sizing属性是一个很大的帮助。 它具有2个值:

  • border-box

    border-box

  • content-box

    content-box

content-box is the default, the one we had for ages before box-sizing became a thing.

content-box是默认选项,在box-sizing成为一种东西之前,我们已经使用了很长时间。

border-box is the new and great thing we are looking for. If you set that on an element:

border-box是我们正在寻找的新奇事物。 如果在元素上进行设置:

.my-div {  box-sizing: border-box;}

width and height calculation include the padding and the border. Only the margin is left out, which is reasonable since in our mind we also typically see that as a separate thing: margin is outside of the box.

宽度和高度的计算包括填充和边框。 仅保留了边距,这是合理的,因为在我们看来,我们通常也将其视为单独的内容:边距不在框内。

This property is a small change but has a big impact. CSS Tricks even declared an , just saying, and it’s recommended to apply it to every element on the page, out of the box, with this:

此属性变化不大,但影响很大。 CSS Tricks甚至宣布了一个 ,只是建议,建议使用此方法将其应用于页面上的每个元素,即开即用:

*, *:before, *:after {  box-sizing: border-box;}

显示 (DISPLAY)

The display property of an object determines how it is rendered by the browser.

对象的display属性确定浏览器如何呈现它。

It’s a very important property, and probably the one with the highest number of values you can use.

这是一个非常重要的属性,并且可能是您可以使用的值数量最多的属性。

Those values include:

这些值包括:

  • block

    block

  • inline

    inline

  • none

    none

  • contents

    contents

  • flow

    flow

  • flow-root

    flow-root

  • table (and all the table-* ones)

    table (以及所有table table-*的表)

  • flex

    flex

  • grid

    grid

  • list-item

    list-item

  • inline-block

    inline-block

  • inline-table

    inline-table

  • inline-flex

    inline-flex

  • inline-grid

    inline-grid

  • inline-list-item

    inline-list-item

plus others you will not likely use, like ruby.

加上其他您不太可能使用的东西,例如ruby

Choosing any of those will considerably alter the behavior of the browser with the element and its children.

选择这些选项中的任何一个都将大大改变带有元素及其子元素的浏览器的行为。

In this section we’ll analyze the most important ones not covered elsewhere:

在本节中,我们将分析其他地方未涵盖的最重要的那些:

  • block

    block

  • inline

    inline

  • inline-block

    inline-block

  • none

    none

We’ll see some of the others in later chapters, including coverage of table, flex and grid.

在后面的章节中,我们将介绍其他一些内容,包括tableflexgrid

inline (inline)

Inline is the default display value for every element in CSS.

内联是CSS中每个元素的默认显示值。

All the HTML tags are displayed inline out of the box except some elements like div, p and section, which are set as block by the user agent (the browser).

除某些元素(例如divpsection )被用户代理(浏览器)设置为block外,所有HTML标记均以开箱即用的方式内联显示。

Inline elements don’t have any margin or padding applied.

内联元素未应用任何边距或填充。

Same for height and width.

高度和宽度相同。

You can add them, but the appearance in the page won’t change — they are calculated and applied automatically by the browser.

可以添加它们,但页面中的外观不会改变-它们是由浏览器自动计算和应用的。

inline-block (inline-block)

Similar to inline, but with inline-block width and height applied as you specify.

inline相似,但根据您的指定应用了inline-block widthheight

block (block)

As mentioned, normally elements are displayed inline, with the exception of some elements, including

如前所述,除了某些元素(包括

  • div

    div

  • p

    p

  • section

    section

  • ul

    ul

which are set as block by the browser.

由浏览器设置为block

With display: block, elements are stacked one after each other, vertically, and every element takes up 100% of the page.

使用display: block ,元素彼此垂直垂直堆叠,每个元素占据页面的100%。

The values assigned to the width and height properties are respected, if you set them, along with margin and padding.

如果进行设置,则会遵守分配给widthheight属性的值,以及marginpadding

none (none)

Using display: none makes an element disappear. It's still there in the HTML, but just not visible in the browser.

使用display: none使元素消失。 它仍然存在于HTML中,但在浏览器中不可见。

定位 (POSITIONING)

Positioning is what makes us determine where elements appear on the screen, and how they appear.

定位使我们能够确定元素在屏幕上的显示位置以及显示方式。

You can move elements around, and position them exactly where you want.

您可以移动元素,然后将它们精确定位在所需的位置。

In this section we’ll also see how things change on a page based on how elements with different position interact with each other.

在本节中,我们还将基于position不同的元素之间的交互方式,了解页面上的事物如何变化。

We have one main CSS property: position.

我们有一个主要CSS属性: position

It can have those 5 values:

它可以具有这5个值:

  • static

    static

  • relative

    relative

  • absolute

    absolute

  • fixed

    fixed

  • sticky

    sticky

静态定位 (Static positioning)

This is the default value for an element. Static positioned elements are displayed in the normal page flow.

这是元素的默认值。 静态定位的元素显示在常规页面流中。

相对定位 (Relative positioning)

If you set position: relative on an element, you are now able to position it with an offset, using the properties

如果在元素上设置position: relative ,则现在可以使用属性以偏移量定位它

  • top

    最佳
  • right

  • bottom

    底部
  • left

    剩下

which are called offset properties. They accept a length value or a percentage.

这称为偏移属性 。 他们接受长度值或百分比。

Take . I create a parent container, a child container, and an inner box with some text:

以 。 我创建一个父容器,一个子容器以及一个带有一些文本的内部框:

Test

with some CSS to give some colors and padding, but does not affect positioning:

使用一些CSS可以提供​​一些颜色和填充,但不影响位置:

.parent {  background-color: #af47ff;  padding: 30px;  width: 300px;}.child {  background-color: #ff4797;  padding: 30px;}.box {  background-color: #f3ff47;  padding: 30px;  border: 2px solid #333;  border-style: dotted;  font-family: courier;  text-align: center;  font-size: 2rem;}

here’s the result:

结果如下:

You can try and add any of the properties I mentioned before (top, right, bottom, left) to .box, and nothing will happen. The position is static.

您可以尝试将我之前提到的任何属性( toprightbottomleft )添加到.box ,什么都不会发生。 该位置是static

Now if we set position: relative to the box, at first apparently nothing changes. But the element is now able to move using the top, right, bottom, left properties, and now you can alter the position of it relatively to the element containing it.

现在,如果我们设置position: relative对于盒子,起初显然没有任何变化。 但是,该元素现在可以使用toprightbottomleft属性移动,现在您可以相对于包含它的元素更改其位置。

For example:

例如:

.box {  /* ... */  position: relative;  top: -60px;}

A negative value for top will make the box move up relatively to its container.

top的负值将使盒子相对于其容器向上移动。

Or

要么

.box {  /* ... */  position: relative;  top: -60px;  left: 180px;}

Notice how the space that is occupied by the box remains preserved in the container, like it was still in its place.

注意,盒子所占据的空间是如何保留在容器中的,就像它仍然在原处一样。

Another property that will now work is z-index to alter the z-axis placement. We'll talk about it later on.

现在可以使用的另一个属性是z-index用于更改z轴位置。 我们稍后再讨论。

绝对定位 (Absolute positioning)

Setting position: absolute on an element will remove it from the document's flow.

设置position: absolute元素上的position: absolute会将其从文档流中删除。

Remember in relative positioning that we noticed the space originally occupied by an element was preserved even if it was moved around?

还记得相对定位时,我们是否注意到元素原本占据的空间被保留了,即使它被移动了吗?

With absolute positioning, as soon as we set position: absolute on .box, its original space is now collapsed, and only the origin (x, y coordinates) remain the same.

使用绝对定位后,只要在.box上设置position: absolute ,它的原始空间现在就会消失,只有原点(x,y坐标)保持不变。

.box {  /* ... */  position: absolute;}

We can now move the box around as we please, using the top, right, bottom, left properties:

现在,我们可以使用toprightbottomleft属性随意移动框:

.box {  /* ... */  position: absolute;  top: 0px;  left: 0px;}

or

要么

.box {  /* ... */  position: absolute;  top: 140px;  left: 50px;}

The coordinates are relative to the closest container that is not static.

坐标是相对于最近的非static容器的。

This means that if we add position: relative to the .child element, and we set top and left to 0, the box will not be positioned at the top left margin of the window, but rather it will be positioned at the 0, 0 coordinates of .child:

这意味着,如果我们添加position: relative对于.child元素的.child并且将topleft设置为0,则该框将不会位于窗口的左上边缘,而是会位于0,0 .child坐标:

.child {  /* ... */  position: relative;}.box {  /* ... */  position: absolute;  top: 0px;  left: 0px;}

Here’s how we already saw that .child is static (the default):

这就是我们已经看到的.child是静态的(默认):

.child {  /* ... */  position: static;}.box {  /* ... */  position: absolute;  top: 0px;  left: 0px;}

Like for relative positioning, you can use z-index to alter the z-axis placement.

与相对定位一样,您可以使用z-index来更改z轴位置。

固定位置 (Fixed positioning)

Like with absolute positioning, when an element is assigned position: fixed it's removed from the flow of the page.

就像绝对定位一样,当为元素分配position: fixed将其从页面流中删除。

The difference with absolute positioning is this: elements are now always positioned relative to the window, instead of the first non-static container.

绝对定位的不同之处在于:元素现在始终相对于窗口而不是第一个非静态容器相对于窗口定位。

.box {  /* ... */  position: fixed;}
.box {  /* ... */  position: fixed;  top: 0;  left: 0;}

Another big difference is that elements are not affected by scrolling. Once you put a sticky element somewhere, scrolling the page does not remove it from the visible part of the page.

另一个很大的不同是元素不受滚动影响。 将粘性元素放置在某处后,滚动页面不会将其从页面的可见部分中删除。

粘性定位 (Sticky positioning)

While the above values have been around for a very long time, this one was introduced recently and it’s still relatively unsupported ()

尽管上述值已经存在很长时间了,但是这个值是最近才引入的,仍然相对不受支持( )

The UITableView iOS component is the thing that comes to mind when I think about position: sticky. You know when you scroll in the contacts list and the first letter is stuck to the top, to let you know you are viewing that particular letter's contacts?

我想到position: sticky时,会想到UITableView iOS组件position: sticky 。 您知道当您在联系人列表中滚动并且第一个字母停留在顶部时,要知道您正在查看该特定字母的联系人吗?

We used JavaScript to emulate that, but this is the approach taken by CSS to allow it natively.

我们使用JavaScript进行了仿真,但这是CSS原生采用的方法。

浮动和清理 (FLOATING AND CLEARING)

Floating has been a very important topic in the past.

过去,浮动是一个非常重要的话题。

It was used in lots of hacks and creative usages because it was one of the few ways, along with tables, we could really implement some layouts. In the past we used to float the sidebar to the left, for example, to show it on the left side of the screen and added some margin to the main content.

它被用于许多技巧和创意用途,因为它是表格和我们可以真正实现某些布局的少数几种方法之一。 过去,我们曾经将边栏浮动到左侧,例如,将其显示在屏幕的左侧,并在主要内容上添加了一些边距。

Luckily times have changed and today we have Flexbox and Grid to help us with layout, and float has gone back to its original scope: placing content on one side of the container element, and making its siblings show up around it.

幸运的是,时代已经发生了变化,如今,我们有了Flexbox和Grid来帮助我们进行布局,而float已回到其原始范围:将内容放置在容器元素的一侧,并使它的兄弟姐妹出现在容器元素的周围。

The float property supports 3 values:

float属性支持3个值:

  • left

    left

  • right

    right

  • none (the default)

    none (默认)

Say we have a box which contains a paragraph with some text, and the paragraph also contains an image.

假设我们有一个框,其中包含带有一些文本的段落,并且该段落还包含图像。

Here’s some code:

这是一些代码:

This is some random paragraph and an image. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text.

.parent { background-color: #af47ff; padding: 30px; width: 500px;}.child { background-color: #ff4797; padding: 30px;}.box { background-color: #f3ff47; padding: 30px; border: 2px solid #333; border-style: dotted; font-family: courier; text-align: justify; font-size: 1rem;}

and the visual appearance:

和视觉外观:

As you can see, the normal flow by default considers the image inline, and makes space for it in the line itself.

如您所见,默认情况下,正常流程会考虑图像内联,并在行本身中为其留出空间。

If we add float: left to the image, and some padding:

如果我们在图像上添加float: left并添加一些填充:

img {  float: left;  padding: 20px 20px 0px 0px;}

this is the result:

结果是:

and this is what we get by applying a float: right, adjusting the padding accordingly:

这就是我们通过应用float来得到的:正确,相应地调整填充:

img {  float: right;  padding: 20px 0px 20px 20px;}

A floated element is removed from the normal flow of the page, and the other content flows around it.

从页面的正常流程中删除浮动元素,其他内容在页面周围流动。

You are not limited to floating images, too. Here we switch the image with a span element:

您也不仅限于浮动图像。 在这里,我们使用span元素切换图像:

This is some random paragraph and an image. Some text to float The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text.

span { float: right; margin: 20px 0px 20px 20px; padding: 10px; border: 1px solid black}

and this is the result:

结果如下:

清算 (Clearing)

What happens when you float more than one element?

当您浮动多个元素时会发生什么?

If when floated they find another floated image, by default they are stacked up one next to the other, horizontally. Until there is no room, and they will start being stacked on a new line.

如果在浮动时找到另一个浮动图像,则默认情况下它们会水平堆叠在一起。 Until there is no room, and they will start being stacked on a new line.

Say we had 3 inline images inside a p tag:

Say we had 3 inline images inside a p tag:

If we add float: left to those images:

If we add float: left to those images:

img {  float: left;  padding: 20px 20px 0px 0px;}

this is what we’ll have:

this is what we'll have:

if you add clear: left to images, those are going to be stacked vertically rather than horizontally:

if you add clear: left to images, those are going to be stacked vertically rather than horizontally:

I used the left value for clear. It allows

I used the left value for clear . It allows

  • left to clear left floats

    left to clear left floats

  • right to clear right floats

    right to clear right floats

  • both to clear both left and right floats

    both to clear both left and right floats

  • none (default) disables clearing

    none (default) disables clearing

Z-INDEX (Z-INDEX)

When we talked about positioning, I mentioned that you can use the z-index property to control the Z axis positioning of elements.

When we talked about positioning, I mentioned that you can use the z-index property to control the Z axis positioning of elements.

It’s very useful when you have multiple elements that overlap each other, and you need to decide which one is visible, as nearer to the user, and which one(s) should be hidden behind it.

It's very useful when you have multiple elements that overlap each other, and you need to decide which one is visible, as nearer to the user, and which one(s) should be hidden behind it.

This property takes a number (without decimals) and uses that number to calculate which elements appear nearer to the user, in the Z axis.

This property takes a number (without decimals) and uses that number to calculate which elements appear nearer to the user, in the Z axis.

The higher the z-index value, the more an element is positioned nearer to the user.

The higher the z-index value, the more an element is positioned nearer to the user.

When deciding which element should be visible and which one should be positioned behind it, the browser does a calculation on the z-index value.

When deciding which element should be visible and which one should be positioned behind it, the browser does a calculation on the z-index value.

The default value is auto, a special keyword. Using auto, the Z axis order is determined by the position of the HTML element in the page - the last sibling appears first, as it's defined last.

The default value is auto , a special keyword. Using auto , the Z axis order is determined by the position of the HTML element in the page - the last sibling appears first, as it's defined last.

By default elements have the static value for the position property. In this case, the z-index property does not make any difference - it must be set to absolute, relative or fixed to work.

By default elements have the static value for the position property. In this case, the z-index property does not make any difference - it must be set to absolute , relative or fixed to work.

Example:

例:

.my-first-div {    position: absolute;    top: 0;    left: 0;    width: 600px;    height: 600px;    z-index: 10;}.my-second-div {    position: absolute;    top: 0;    left: 0;    width: 500px;    height: 500px;    z-index: 20;}

The element with class .my-second-div will be displayed, and behind it .my-first-div.

The element with class .my-second-div will be displayed, and behind it .my-first-div .

Here we used 10 and 20, but you can use any number. Negative numbers too. It’s common to pick non-consecutive numbers, so you can position elements in the middle. If you use consecutive numbers instead, you would need to re-calculate the z-index of each element involved in the positioning.

Here we used 10 and 20, but you can use any number. Negative numbers too. It's common to pick non-consecutive numbers, so you can position elements in the middle. If you use consecutive numbers instead, you would need to re-calculate the z-index of each element involved in the positioning.

CSS GRID (CSS GRID)

CSS Grid is the new kid in the CSS town, and while not yet fully supported by all browsers, it’s going to be the future system for layouts.

CSS Grid is the new kid in the CSS town, and while not yet fully supported by all browsers, it's going to be the future system for layouts.

CSS Grid is a fundamentally new approach to building layouts using CSS.

CSS Grid is a fundamentally new approach to building layouts using CSS.

Keep an eye on the CSS Grid Layout page on caniuse.com () to find out which browsers currently support it. At the time of writing, April 2019, all major browsers (except IE, which will never have support for it) are already supporting this technology, covering 92% of all users.

Keep an eye on the CSS Grid Layout page on caniuse.com ( ) to find out which browsers currently support it. At the time of writing, April 2019, all major browsers (except IE, which will never have support for it) are already supporting this technology, covering 92% of all users.

CSS Grid is not a competitor to Flexbox. They interoperate and collaborate on complex layouts, because CSS Grid works on 2 dimensions (rows AND columns) while Flexbox works on a single dimension (rows OR columns).

CSS Grid is not a competitor to Flexbox. They interoperate and collaborate on complex layouts, because CSS Grid works on 2 dimensions (rows AND columns) while Flexbox works on a single dimension (rows OR columns).

Building layouts for the web has traditionally been a complicated topic.

Building layouts for the web has traditionally been a complicated topic.

I won’t dig into the reasons for this complexity, which is a complex topic on its own. But you can think yourself as a very lucky human because nowadays you have 2 very powerful and well supported tools at your disposal:

I won't dig into the reasons for this complexity, which is a complex topic on its own. But you can think yourself as a very lucky human because nowadays you have 2 very powerful and well supported tools at your disposal:

  • CSS Flexbox

    CSS Flexbox

  • CSS Grid

    CSS网格

These 2 are the tools to build the Web layouts of the future.

These 2 are the tools to build the Web layouts of the future.

Unless you need to support old browsers like IE8 and IE9, there is no reason to be messing with things like:

Unless you need to support old browsers like IE8 and IE9, there is no reason to be messing with things like:

  • Table layouts

    Table layouts
  • Floats

    浮点数
  • clearfix hacks

    clearfix hacks
  • display: table hacks

    display: table hacks

In this guide there’s all you need to know about going from zero knowledge of CSS Grid to being a proficient user.

In this guide there's all you need to know about going from zero knowledge of CSS Grid to being a proficient user.

基础 (The basics)

The CSS Grid layout is activated on a container element (which can be a div or any other tag) by setting display: grid.

The CSS Grid layout is activated on a container element (which can be a div or any other tag) by setting display: grid .

As with flexbox, you can define some properties on the container, and some properties on each individual item in the grid.

As with flexbox, you can define some properties on the container, and some properties on each individual item in the grid.

These properties combined will determine the final look of the grid.

These properties combined will determine the final look of the grid.

The most basic container properties are grid-template-columns and grid-template-rows.

The most basic container properties are grid-template-columns and grid-template-rows .

grid-template-columns and grid-template-rows (grid-template-columns and grid-template-rows)

Those properties define the number of columns and rows in the grid, and they also set the width of each column/row.

Those properties define the number of columns and rows in the grid, and they also set the width of each column/row.

The following snippet defines a grid with 4 columns each 200px wide, and 2 rows with a 300px height each.

The following snippet defines a grid with 4 columns each 200px wide, and 2 rows with a 300px height each.

.container {  display: grid;  grid-template-columns: 200px 200px 200px 200px;  grid-template-rows: 300px 300px;}

Here’s another example of a grid with 2 columns and 2 rows:

Here's another example of a grid with 2 columns and 2 rows:

.container {  display: grid;  grid-template-columns: 200px 200px;  grid-template-rows: 100px 100px;}

Automatic dimensions (Automatic dimensions)

Many times you might have a fixed header size, a fixed footer size, and the main content that is flexible in height, depending on its length. In this case you can use the auto keyword:

Many times you might have a fixed header size, a fixed footer size, and the main content that is flexible in height, depending on its length. In this case you can use the auto keyword:

.container {  display: grid;  grid-template-rows: 100px auto 100px;}

Different columns and rows dimensions (Different columns and rows dimensions)

In the above examples we made regular grids by using the same values for rows and the same values for columns.

In the above examples we made regular grids by using the same values for rows and the same values for columns.

You can specify any value for each row/column, to create a lot of different designs:

You can specify any value for each row/column, to create a lot of different designs:

.container {  display: grid;  grid-template-columns: 100px 200px;  grid-template-rows: 100px 50px;}

Another example:

另一个例子:

.container {  display: grid;  grid-template-columns: 10px 100px;  grid-template-rows: 100px 10px;}

Adding space between the cells (Adding space between the cells)

Unless specified, there is no space between the cells.

Unless specified, there is no space between the cells.

You can add spacing by using those properties:

You can add spacing by using those properties:

  • grid-column-gap

    grid-column-gap

  • grid-row-gap

    grid-row-gap

or the shorthand syntax grid-gap.

or the shorthand syntax grid-gap .

Example:

例:

.container {  display: grid;  grid-template-columns: 100px 200px;  grid-template-rows: 100px 50px;  grid-column-gap: 25px;  grid-row-gap: 25px;}

The same layout using the shorthand:

The same layout using the shorthand:

.container {  display: grid;  grid-template-columns: 100px 200px;  grid-template-rows: 100px 50px;  grid-gap: 25px;}

Spawning items on multiple columns and/or rows (Spawning items on multiple columns and/or rows)

Every cell item has the option to occupy more than just one box in the row, and expand horizontally or vertically to get more space, while respecting the grid proportions set in the container.

Every cell item has the option to occupy more than just one box in the row, and expand horizontally or vertically to get more space, while respecting the grid proportions set in the container.

These are the properties we’ll use for that:

These are the properties we'll use for that:

  • grid-column-start

    grid-column-start

  • grid-column-end

    grid-column-end

  • grid-row-start

    grid-row-start

  • grid-row-end

    grid-row-end

Example:

例:

.container {  display: grid;  grid-template-columns: 200px 200px 200px 200px;  grid-template-rows: 300px 300px;}.item1 {  grid-column-start: 2;  grid-column-end: 4;}.item6 {  grid-column-start: 3;  grid-column-end: 5;}

The numbers correspond to the vertical line that separates each column, starting from 1:

The numbers correspond to the vertical line that separates each column, starting from 1:

The same principle applies to grid-row-start and grid-row-end, except this time instead of taking more columns, a cell takes more rows.

The same principle applies to grid-row-start and grid-row-end , except this time instead of taking more columns, a cell takes more rows.

Shorthand syntax (Shorthand syntax)

Those properties have a shorthand syntax provided by:

Those properties have a shorthand syntax provided by:

  • grid-column

    grid-column

  • grid-row

    grid-row

The usage is simple, here’s how to replicate the above layout:

The usage is simple, here's how to replicate the above layout:

.container {  display: grid;  grid-template-columns: 200px 200px 200px 200px;  grid-template-rows: 300px 300px;}.item1 {  grid-column: 2 / 4;}.item6 {  grid-column: 3 / 5;}

Another approach is to set the starting column/row, and set how many it should occupy using span:

Another approach is to set the starting column/row, and set how many it should occupy using span :

.container {  display: grid;  grid-template-columns: 200px 200px 200px 200px;  grid-template-rows: 300px 300px;}.item1 {  grid-column: 2 / span 2;}.item6 {  grid-column: 3 / span 2;}

More grid configuration (More grid configuration)

Using fractions (Using fractions)

Specifying the exact width of each column or row is not ideal in every case.

Specifying the exact width of each column or row is not ideal in every case.

A fraction is a unit of space.

A fraction is a unit of space.

The following example divides a grid into 3 columns with the same width, 1/3 of the available space each.

The following example divides a grid into 3 columns with the same width, 1/3 of the available space each.

.container {  grid-template-columns: 1fr 1fr 1fr;}

Using percentages and rem (Using percentages and rem)

You can also use percentages, and mix and match fractions, pixels, rem and percentages:

You can also use percentages, and mix and match fractions, pixels, rem and percentages:

.container {  grid-template-columns: 3rem 15% 1fr 2fr}

Using repeat() (Using repeat())

repeat() is a special function that takes a number that indicates the number of times a row/column will be repeated, and the length of each one.

repeat() is a special function that takes a number that indicates the number of times a row/column will be repeated, and the length of each one.

If every column has the same width, you can specify the layout using this syntax:

If every column has the same width, you can specify the layout using this syntax:

.container {  grid-template-columns: repeat(4, 100px);}

This creates 4 columns with the same width.

This creates 4 columns with the same width.

Or using fractions:

Or using fractions:

.container {  grid-template-columns: repeat(4, 1fr);}

Specify a minimum width for a row (Specify a minimum width for a row)

Common use case: Have a sidebar that never collapses more than a certain amount of pixels when you resize the window.

Common use case: Have a sidebar that never collapses more than a certain amount of pixels when you resize the window.

Here’s an example where the sidebar takes 1/4 of the screen and never takes less than 200px:

Here's an example where the sidebar takes 1/4 of the screen and never takes less than 200px:

.container {  grid-template-columns: minmax(200px, 3fr) 9fr;}

You can also set just a maximum value using the auto keyword:

You can also set just a maximum value using the auto keyword:

.container {  grid-template-columns: minmax(auto, 50%) 9fr;}

or just a minimum value:

or just a minimum value:

.container {  grid-template-columns: minmax(100px, auto) 9fr;}

Positioning elements using grid-template-areas (Positioning elements using grid-template-areas)

By default elements are positioned in the grid using their order in the HTML structure.

By default elements are positioned in the grid using their order in the HTML structure.

Using grid-template-areas you can define template areas to move them around in the grid, and also to spawn an item on multiple rows / columns instead of using grid-column.

Using grid-template-areas you can define template areas to move them around in the grid, and also to spawn an item on multiple rows / columns instead of using grid-column .

Here’s an example:

这是一个例子:

...
...
...
.container { display: grid; grid-template-columns: 200px 200px 200px 200px; grid-template-rows: 300px 300px; grid-template-areas: "header header header header" "sidebar main main main" "footer footer footer footer";}main { grid-area: main;}aside { grid-area: sidebar;}header { grid-area: header;}footer { grid-area: footer;}

Despite their original order, items are placed where grid-template-areas define, depending on the grid-area property associated to them.

Despite their original order, items are placed where grid-template-areas define, depending on the grid-area property associated to them.

Adding empty cells in template areas (Adding empty cells in template areas)

You can set an empty cell using the dot . instead of an area name in grid-template-areas:

You can set an empty cell using the dot . instead of an area name in grid-template-areas :

.container {  display: grid;  grid-template-columns: 200px 200px 200px 200px;  grid-template-rows: 300px 300px;  grid-template-areas:    ". header header ."    "sidebar . main main"    ". footer footer .";}

Fill a page with a grid (Fill a page with a grid)

You can make a grid extend to fill the page using fr:

You can make a grid extend to fill the page using fr :

.container {  display: grid;  height: 100vh;  grid-template-columns: 1fr 1fr 1fr 1fr;  grid-template-rows: 1fr 1fr;}

Here is a simple example of using CSS Grid to create a site layout that provides a header op top, a main part with sidebar on the left and content on the right, and a footer afterwards.

Here is a simple example of using CSS Grid to create a site layout that provides a header op top, a main part with sidebar on the left and content on the right, and a footer afterwards.

Here’s the markup:

Here's the markup:

Header

Welcome

Hi!

Footer

and here’s the CSS:

and here's the CSS:

header {  grid-area: header;  background-color: #fed330;  padding: 20px;}article {  grid-area: content;  background-color: #20bf6b;  padding: 20px;}aside {  grid-area: sidebar;  background-color: #45aaf2;}footer {  padding: 20px;  grid-area: footer;  background-color: #fd9644;}.wrapper {  display: grid;  grid-gap: 20px;  grid-template-columns: 1fr 3fr;  grid-template-areas:    "header  header"    "sidebar content"    "footer  footer";}

I added some colors to make it prettier, but basically it assigns to every different tag a grid-area name, which is used in the grid-template-areas property in .wrapper.

I added some colors to make it prettier, but basically it assigns to every different tag a grid-area name, which is used in the grid-template-areas property in .wrapper .

When the layout is smaller we can put the sidebar below the content using a media query:

When the layout is smaller we can put the sidebar below the content using a media query:

@media (max-width: 500px) {  .wrapper {    grid-template-columns: 4fr;    grid-template-areas:      "header"      "content"      "sidebar"      "footer";  }}

These are the basics of CSS Grid. There are many things I didn’t include in this introduction but I wanted to make it very simple, so you can start using this new layout system without making it feel overwhelming.

These are the basics of CSS Grid. There are many things I didn't include in this introduction but I wanted to make it very simple, so you can start using this new layout system without making it feel overwhelming.

FLEXBOX (FLEXBOX)

Flexbox, also called Flexible Box Module, is one of the two modern layouts systems, along with CSS Grid.

Flexbox, also called Flexible Box Module, is one of the two modern layouts systems, along with CSS Grid.

Compared to CSS Grid (which is bi-dimensional), flexbox is a one-dimensional layout model. It will control the layout based on a row or on a column, but not together at the same time.

Compared to CSS Grid (which is bi-dimensional), flexbox is a one-dimensional layout model . It will control the layout based on a row or on a column, but not together at the same time.

The main goal of flexbox is to allow items to fill the whole space offered by their container, depending on some rules you set.

The main goal of flexbox is to allow items to fill the whole space offered by their container, depending on some rules you set.

Unless you need to support old browsers like IE8 and IE9, Flexbox is the tool that lets you forget about using

Unless you need to support old browsers like IE8 and IE9, Flexbox is the tool that lets you forget about using

  • Table layouts

    Table layouts
  • Floats

    浮点数
  • clearfix hacks

    clearfix hacks
  • display: table hacks

    display: table hacks

Let’s dive into flexbox and become a master of it in a very short time.

Let's dive into flexbox and become a master of it in a very short time.

浏览器支持 (Browser support)

At the time of writing (Feb 2018), it’s supported by 97.66% of the users. All the most important browsers have implemented it for years, so even older browsers (including IE10+) are covered:

At the time of writing (Feb 2018), it's supported by 97.66% of the users. All the most important browsers have implemented it for years, so even older browsers (including IE10+) are covered:

While we must wait a few years for users to catch up on CSS Grid, Flexbox is an older technology and can be used right now.

While we must wait a few years for users to catch up on CSS Grid, Flexbox is an older technology and can be used right now.

Enable Flexbox (Enable Flexbox)

A flexbox layout is applied to a container, by setting

A flexbox layout is applied to a container, by setting

display: flex;

or

要么

display: inline-flex;

The content inside the container will be aligned using flexbox.

The content inside the container will be aligned using flexbox.

Container properties (Container properties)

Some flexbox properties apply to the container, which sets the general rules for its items. They are

Some flexbox properties apply to the container, which sets the general rules for its items. 他们是

  • flex-direction

    flex-direction

  • justify-content

    justify-content

  • align-items

    align-items

  • flex-wrap

    flex-wrap

  • flex-flow

    flex-flow

Align rows or columns (Align rows or columns)

The first property we see, flex-direction, determines if the container should align its items as rows, or as columns:

The first property we see, flex-direction , determines if the container should align its items as rows, or as columns:

  • flex-direction: row places items as a row, in the text direction (left-to-right for western countries)

    flex-direction: row places items as a row , in the text direction (left-to-right for western countries)

  • flex-direction: row-reverse places items just like row but in the opposite direction

    flex-direction: row-reverse places items just like row but in the opposite direction

  • flex-direction: column places items in a column, ordering top to bottom

    flex-direction: column places items in a column , ordering top to bottom

  • flex-direction: column-reverse places items in a column, just like column but in the opposite direction

    flex-direction: column-reverse places items in a column, just like column but in the opposite direction

Vertical and horizontal alignment (Vertical and horizontal alignment)

By default, items start from the left if flex-direction is row, and from the top if flex-direction is column.

By default, items start from the left if flex-direction is row, and from the top if flex-direction is column.

You can change this behavior using justify-content to change the horizontal alignment, and align-items to change the vertical alignment.

You can change this behavior using justify-content to change the horizontal alignment, and align-items to change the vertical alignment.

Change the horizontal alignment (Change the horizontal alignment)

justify-content has 5 possible values:

justify-content has 5 possible values:

  • flex-start: align to the left side of the container.

    flex-start : align to the left side of the container.

  • flex-end: align to the right side of the container.

    flex-end : align to the right side of the container.

  • center: align at the center of the container.

    center : align at the center of the container.

  • space-between: display with equal spacing between them.

    space-between : display with equal spacing between them.

  • space-around: display with equal spacing around them

    space-around : display with equal spacing around them

Change the vertical alignment (Change the vertical alignment)

align-items has 5 possible values:

align-items has 5 possible values:

  • flex-start: align to the top of the container.

    flex-start : align to the top of the container.

  • flex-end: align to the bottom of the container.

    flex-end : align to the bottom of the container.

  • center: align at the vertical center of the container.

    center : align at the vertical center of the container.

  • baseline: display at the baseline of the container.

    baseline : display at the baseline of the container.

  • stretch: items are stretched to fit the container.

    stretch : items are stretched to fit the container.

A note on baseline:

A note on baseline :

baseline looks similar to flex-start in this example, due to my boxes being too simple. Check out to have a more useful example, which I forked from a Pen originally created by . As you can see there, item dimensions are aligned.

baseline looks similar to flex-start in this example, due to my boxes being too simple. Check out to have a more useful example, which I forked from a Pen originally created by . As you can see there, item dimensions are aligned.

(Wrap)

By default, items in a flexbox container are kept on a single line, shrinking them to fit in the container.

By default, items in a flexbox container are kept on a single line, shrinking them to fit in the container.

To force the items to spread across multiple lines, use flex-wrap: wrap. This will distribute the items according to the order set in flex-direction. Use flex-wrap: wrap-reverse to reverse this order.

To force the items to spread across multiple lines, use flex-wrap: wrap . This will distribute the items according to the order set in flex-direction . Use flex-wrap: wrap-reverse to reverse this order.

A shorthand property called flex-flow allows you to specify flex-direction and flex-wrap in a single line, by adding the flex-direction value first, followed by flex-wrap value, for example: flex-flow: row wrap.

A shorthand property called flex-flow allows you to specify flex-direction and flex-wrap in a single line, by adding the flex-direction value first, followed by flex-wrap value, for example: flex-flow: row wrap .

Properties that apply to each single item (Properties that apply to each single item)

Up to this point, we’ve seen the properties you can apply to the container.

Up to this point, we've seen the properties you can apply to the container.

Single items can have a certain amount of independence and flexibility, and you can alter their appearance using those properties:

Single items can have a certain amount of independence and flexibility, and you can alter their appearance using those properties:

  • order

    order

  • align-self

    align-self

  • flex-grow

    flex-grow

  • flex-shrink

    flex-shrink

  • flex-basis

    flex-basis

  • flex

    flex

Let’s see them in detail.

让我们详细了解它们。

Moving items before / after another one using order (Moving items before / after another one using order)

Items are ordered based on the order they are assigned. By default every item has order 0 and the appearance in the HTML determines the final order.

Items are ordered based on the order they are assigned. By default every item has order 0 and the appearance in the HTML determines the final order.

You can override this property using order on each separate item. This is a property you set on the item, not the container. You can make an item appear before all the others by setting a negative value.

You can override this property using order on each separate item. This is a property you set on the item, not the container. You can make an item appear before all the others by setting a negative value.

Vertical alignment using align-self (Vertical alignment using align-self)

An item can choose to override the container align-items setting, using align-self, which has the same 5 possible values of align-items:

An item can choose to override the container align-items setting, using align-self , which has the same 5 possible values of align-items :

  • flex-start: align to the top of the container.

    flex-start : align to the top of the container.

  • flex-end: align to the bottom of the container.

    flex-end : align to the bottom of the container.

  • center: align at the vertical center of the container.

    center : align at the vertical center of the container.

  • baseline: display at the baseline of the container.

    baseline : display at the baseline of the container.

  • stretch: items are stretched to fit the container.

    stretch : items are stretched to fit the container.

Grow or shrink an item if necessary (Grow or shrink an item if necessary)

flex-grow

flex-grow

The defaut for any item is 0.

The defaut for any item is 0.

If all items are defined as 1 and one is defined as 2, the bigger element will take the space of two “1” items.

If all items are defined as 1 and one is defined as 2, the bigger element will take the space of two “1” items.

flex-shrink

flex-shrink

The defaut for any item is 1.

The defaut for any item is 1.

If all items are defined as 1 and one is defined as 3, the bigger element will shrink 3x the other ones. When less space is available, it will take 3x less space.

If all items are defined as 1 and one is defined as 3, the bigger element will shrink 3x the other ones. When less space is available, it will take 3x less space.

flex-basis

flex-basis

If set to auto, it sizes an item according to its width or height, and adds extra space based on the flex-grow property.

If set to auto , it sizes an item according to its width or height, and adds extra space based on the flex-grow property.

If set to 0, it does not add any extra space for the item when calculating the layout.

If set to 0, it does not add any extra space for the item when calculating the layout.

If you specify a pixel number value, it will use that as the length value (width or height depends on if it’s a row or a column item)

If you specify a pixel number value, it will use that as the length value (width or height depends on if it's a row or a column item)

flex

flex

This property combines the above 3 properties:

This property combines the above 3 properties:

  • flex-grow

    flex-grow

  • flex-shrink

    flex-shrink

  • flex-basis

    flex-basis

and provides a shorthand syntax: flex: 0 1 auto

and provides a shorthand syntax: flex: 0 1 auto

TABLES (TABLES)

Tables in the past were greatly overused in CSS, as they were one of the only ways we could create a fancy page layout.

Tables in the past were greatly overused in CSS, as they were one of the only ways we could create a fancy page layout.

Today with Grid and Flexbox we can move tables back to the job they were intended to do: styling tables.

Today with Grid and Flexbox we can move tables back to the job they were intended to do: styling tables.

Let’s start from the HTML. This is a basic table:

Let's start from the HTML. This is a basic table:

Name Age
Flavio 36
Roger 7

By default it’s not very attractive. The browser provides some standard styles, and that’s it:

By default it's not very attractive. The browser provides some standard styles, and that's it:

We can use CSS to style all the elements of the table, of course.

We can use CSS to style all the elements of the table, of course.

Let’s start with the border. A nice border can go a long way.

Let's start with the border. A nice border can go a long way.

We can apply it on the table element, and on the inner elements too, like th and td:

We can apply it on the table element, and on the inner elements too, like th and td :

table, th, td {  border: 1px solid #333;}

If we pair it with some margin, we get a nice result:

If we pair it with some margin, we get a nice result:

One common thing with tables is the ability to add a color to one row, and a different color to another row. This is possible using the :nth-child(odd) or :nth-child(even) selector:

One common thing with tables is the ability to add a color to one row, and a different color to another row. This is possible using the :nth-child(odd) or :nth-child(even) selector:

tbody tr:nth-child(odd) {  background-color: #af47ff;}

This gives us:

This gives us:

If you add border-collapse: collapse; to the table element, all borders are collapsed into one:

If you add border-collapse: collapse; to the table element, all borders are collapsed into one:

CENTERING (CENTERING)

Centering things in CSS is a task that is very different if you need to center horizontally or vertically.

Centering things in CSS is a task that is very different if you need to center horizontally or vertically.

In this post I explain the most common scenarios and how to solve them. If a new solution is provided by I ignore the old techniques because we need to move forward, and Flexbox has been supported by browsers for years, IE10 included.

In this post I explain the most common scenarios and how to solve them. If a new solution is provided by I ignore the old techniques because we need to move forward, and Flexbox has been supported by browsers for years, IE10 included.

Center horizontally (Center horizontally)

文本 (Text)

Text is very simple to center horizontally using the text-align property set to center:

Text is very simple to center horizontally using the text-align property set to center :

p {  text-align: center;}

积木 (Blocks)

The modern way to center anything that is not text is to use Flexbox:

The modern way to center anything that is not text is to use Flexbox:

#mysection {  display: flex;  justify-content: center;}

any element inside #mysection will be horizontally centered.

any element inside #mysection will be horizontally centered.

Here is the alternative approach if you don’t want to use Flexbox.

Here is the alternative approach if you don't want to use Flexbox.

Anything that is not text can be centered by applying an automatic margin to left and right, and setting the width of the element:

Anything that is not text can be centered by applying an automatic margin to left and right, and setting the width of the element:

section {  margin: 0 auto;  width: 50%;}

the above margin: 0 auto; is a shorthand for:

the above margin: 0 auto; is a shorthand for:

section {  margin-top: 0;  margin-bottom: 0;  margin-left: auto;  margin-right: auto;}

Remember to set the item to display: block if it's an inline element.

Remember to set the item to display: block if it's an inline element.

Center vertically (Center vertically)

Traditionally this has always been a difficult task. Flexbox now provides us a great way to do this in the simplest possible way:

Traditionally this has always been a difficult task. Flexbox now provides us a great way to do this in the simplest possible way:

#mysection {  display: flex;  align-items: center;}

any element inside #mysection will be vertically centered.

any element inside #mysection will be vertically centered.

Center both vertically and horizontally (Center both vertically and horizontally)

Flexbox techniques to center vertically and horizontally can be combined to completely center an element in the page.

Flexbox techniques to center vertically and horizontally can be combined to completely center an element in the page.

#mysection {  display: flex;  align-items: center;  justify-content: center;}

The same can be done using :

The same can be done using :

body {  display: grid;  place-items: center;  height: 100vh;}

LISTS (LISTS)

Lists are a very important part of many web pages.

Lists are a very important part of many web pages.

CSS can style them using several properties.

CSS can style them using several properties.

list-style-type is used to set a predefined marker to be used by the list:

list-style-type is used to set a predefined marker to be used by the list:

li {  list-style-type: square;}

We have lots of possible values, which you can see here with examples of their appearance. Some of the most popular ones are disc, circle, square and none.

We have lots of possible values, which you can see here with examples of their appearance. Some of the most popular ones are disc , circle , square and none .

list-style-image is used to use a custom marker when a predefined marker is not appropriate:

list-style-image is used to use a custom marker when a predefined marker is not appropriate:

li {  list-style-image: url(list-image.png);}

list-style-position lets you add the marker outside (the default) or inside of the list content, in the flow of the page rather than outside of it

list-style-position lets you add the marker outside (the default) or inside of the list content, in the flow of the page rather than outside of it

li {  list-style-position: inside;}

The list-style shorthand property lets us specify all those properties in the same line:

The list-style shorthand property lets us specify all those properties in the same line:

li {  list-style: url(list-image.png) inside;}

MEDIA QUERIES AND RESPONSIVE DESIGN (MEDIA QUERIES AND RESPONSIVE DESIGN)

In this section we’re going to first introduce media types and media feature descriptors, then we’ll explain media queries.

In this section we're going to first introduce media types and media feature descriptors, then we'll explain media queries.

Media types (Media types)

Used in media queries and @import declarations, media types allow us to determine on which media a CSS file, or a piece of CSS, is loaded.

Used in media queries and @import declarations, media types allow us to determine on which media a CSS file, or a piece of CSS, is loaded.

We have the following media types

We have the following media types

  • all means all the media

    all means all the media

  • print used when printing

    print used when printing

  • screen used when the page is presented on a screen

    screen used when the page is presented on a screen

  • speech used for screen readers

    speech used for screen readers

screen is the default.

screen is the default.

In the past we had more of them, but most are deprecated as they proved to be ineffective ways of determining device needs.

In the past we had more of them, but most are deprecated as they proved to be ineffective ways of determining device needs.

We can use them in @import statements like this:

We can use them in @import statements like this:

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

We can load a CSS file on multiple media types separating each with a comma:

We can load a CSS file on multiple media types separating each with a comma:

@import url(myfile.css) screen, print;

The same works for the link tag in HTML:

The same works for the link tag in HTML:

We’re not limited to just using media types in the media attribute and in the @import declaration. There's more.

We're not limited to just using media types in the media attribute and in the @import declaration. There's more.

Media feature descriptors (Media feature descriptors)

First, let’s introduce media feature descriptors. They are additional keywords that we can add to the media attribute of link or the the @import declaration, to express more conditionals over the loading of the CSS.

First, let's introduce media feature descriptors . They are additional keywords that we can add to the media attribute of link or the the @import declaration, to express more conditionals over the loading of the CSS.

Here’s the list of them:

Here's the list of them:

  • width

    width

  • height

    height

  • device-width

    device-width

  • device-height

    device-height

  • aspect-ratio

    aspect-ratio

  • device-aspect-ratio

    device-aspect-ratio

  • color

    color

  • color-index

    color-index

  • monochrome

    monochrome

  • resolution

    resolution

  • orientation

    orientation

  • scan

    scan

  • grid

    grid

Each of them has a corresponding min- and max-, for example:

Each of them has a corresponding min- and max- , for example:

  • min-width, max-width

    min-width , max-width

  • min-device-width, max-device-width

    min-device-width , max-device-width

and so on.

等等。

Some of those accept a length value which can be expressed in px or rem or any length value. It's the case of width, height, device-width, device-height.

Some of those accept a length value which can be expressed in px or rem or any length value. It's the case of width , height , device-width , device-height .

For example:

例如:

@import url(myfile.css) screen and (max-width: 800px);

Notice that we wrap each block using media feature descriptors in parentheses.

Notice that we wrap each block using media feature descriptors in parentheses.

Some accept a fixed value. orientation, used to detect the device orientation, accepts portrait or landscape.

Some accept a fixed value. orientation , used to detect the device orientation, accepts portrait or landscape .

Example:

例:

scan, used to determine the type of screen, accepts progressive (for modern displays) or interlace (for older CRT devices).

scan , used to determine the type of screen, accepts progressive (for modern displays) or interlace (for older CRT devices).

Some others want an integer.

Some others want an integer.

Like color which inspects the number of bits per color component used by the device. Very low-level, but you just need to know it's there for your usage (like grid, color-index, monochrome).

Like color which inspects the number of bits per color component used by the device. Very low-level, but you just need to know it's there for your usage (like grid , color-index , monochrome ).

aspect-ratio and device-aspect-ratio accept a ratio value representing the width to height viewport ratio, which is expressed as a fraction.

aspect-ratio and device-aspect-ratio accept a ratio value representing the width to height viewport ratio, which is expressed as a fraction.

Example:

例:

@import url(myfile.css) screen and (aspect-ratio: 4/3);

resolution represents the pixel density of the device, expressed in a like dpi.

resolution represents the pixel density of the device, expressed in a like dpi .

Example:

例:

@import url(myfile.css) screen and (min-resolution: 100dpi);

Logic operators (Logic operators)

We can combine rules using and:

We can combine rules using and :

We can perform an “or” type of logic operation using commas, which combines multiple media queries:

We can perform an “or” type of logic operation using commas, which combines multiple media queries:

@import url(myfile.css) screen, print;

We can use not to negate a media query:

We can use not to negate a media query:

@import url(myfile.css) not screen;

Important: not can only be used to negate an entire media query, so it must be placed at the beginning of it (or after a comma).

Important: not can only be used to negate an entire media query, so it must be placed at the beginning of it (or after a comma).

媒体查询 (Media queries)

All those above rules we saw applied to @import or the the link HTML tag can be applied inside the CSS, too.

All those above rules we saw applied to @import or the the link HTML tag can be applied inside the CSS, too.

You need to wrap them in a @media () {} structure.

You need to wrap them in a @media () {} structure.

Example:

例:

@media screen and (max-width: 800px) {  /* enter some CSS */}

and this is the foundation for responsive design.

and this is the foundation for responsive design .

Media queries can be quite complex. This example applies the CSS only if it’s a screen device, the width is between 600 and 800 pixels, and the orientation is landscape:

Media queries can be quite complex. This example applies the CSS only if it's a screen device, the width is between 600 and 800 pixels, and the orientation is landscape:

@media screen and (max-width: 800px) and (min-width: 600px) and (orientation: landscape) {  /* enter some CSS */}

FEATURE QUERIES (FEATURE QUERIES)

Feature queries are a recent and relatively unknown ability of CSS, but a one.

Feature queries are a recent and relatively unknown ability of CSS, but a one.

We can use it to check if a feature is supported by the browser using the @supports keyword.

We can use it to check if a feature is supported by the browser using the @supports keyword.

I think this is especially useful, at the time of writing, for checking if a browser supports CSS grid, for example, which can be done using:

I think this is especially useful, at the time of writing, for checking if a browser supports CSS grid, for example, which can be done using:

@supports (display: grid) {  /* apply this CSS */}

We check if the browser supports the grid value for the display property.

We check if the browser supports the grid value for the display property.

We can use @supports for any CSS property, to check any value.

We can use @supports for any CSS property, to check any value.

We can also use the logical operators and, or and not to build complex feature queries:

We can also use the logical operators and , or and not to build complex feature queries:

@supports (display: grid) and (display: flex) {  /* apply this CSS */}

FILTERS (FILTERS)

Filters allow us to perform operations on elements.

Filters allow us to perform operations on elements.

Things you normally do with Photoshop or other photo editing software, like changing the opacity or the brightness, and more.

Things you normally do with Photoshop or other photo editing software, like changing the opacity or the brightness, and more.

You use the filter property. Here's an example of it applied on an image, but this property can be used on any element:

You use the filter property. Here's an example of it applied on an image, but this property can be used on any element:

img {  filter: 
;}

You can use various values here:

You can use various values here:

  • blur()

    blur()

  • brightness()

    brightness()

  • contrast()

    contrast()

  • drop-shadow()

    drop-shadow()

  • grayscale()

    grayscale()

  • hue-rotate()

    hue-rotate()

  • invert()

    invert()

  • opacity()

    opacity()

  • sepia()

    sepia()

  • saturate()

    saturate()

  • url()

    url()

Notice the parentheses after each option, because they all require a parameter.

Notice the parentheses after each option, because they all require a parameter.

For example:

例如:

img {  filter: opacity(0.5);}

means the image will be 50% transparent, because opacity() takes one value from 0 to 1, or a percentage.

means the image will be 50% transparent, because opacity() takes one value from 0 to 1, or a percentage.

You can also apply multiple filters at once:

You can also apply multiple filters at once:

img {  filter: opacity(0.5) blur(2px);}

Let’s now talk about each filter in detail.

Let's now talk about each filter in detail.

blur() (blur())

Blurs an element content. You pass it a value, expressed in px or em or rem that will be used to determine the blur radius.

Blurs an element content. You pass it a value, expressed in px or em or rem that will be used to determine the blur radius.

Example:

例:

img {  filter: blur(4px);}

opacity() (opacity())

opacity() takes one value from 0 to 1, or a percentage, and determines the image transparency based on it.

opacity() takes one value from 0 to 1, or a percentage, and determines the image transparency based on it.

0, or 0%, means totally transparent. 1, or 100%, or higher, means totally visible.

0 , or 0% , means totally transparent. 1 , or 100% , or higher, means totally visible.

Example:

例:

img {  filter: opacity(0.5);}

CSS also has an opacity property. filter however can be hardware accelerated, depending on the implementation, so this should be the preferred method.

CSS also has an opacity property. filter however can be hardware accelerated, depending on the implementation, so this should be the preferred method.

drop-shadow() (drop-shadow())

drop-shadow() shows a shadow behind the element, which follows the alpha channel. This means that if you have a transparent image, you get a shadow applied to the image shape, not the image box. If the image does not have an alpha channel, the shadow will be applied to the entire image box.

drop-shadow() shows a shadow behind the element, which follows the alpha channel. This means that if you have a transparent image, you get a shadow applied to the image shape, not the image box. If the image does not have an alpha channel, the shadow will be applied to the entire image box.

It accepts a minimum of 2 parameters, up to 5:

It accepts a minimum of 2 parameters, up to 5:

  • offset-x sets the horizontal offset. Can be negative.

    offset-x sets the horizontal offset. Can be negative.

  • offset-y sets the vertical offset. Can be negative.

    offset-y sets the vertical offset. Can be negative.

  • blur-radius, optional, sets the blur radius for the shadow. It defaults to 0, no blur.

    blur-radius , optional, sets the blur radius for the shadow. It defaults to 0, no blur.

  • spread-radius, optional, sets the spread radius. Expressed in px, rem or em

    spread-radius , optional, sets the spread radius. Expressed in px , rem or em

  • color, optional, sets the color of the shadow.

    color , optional, sets the color of the shadow.

You can set the color without setting the spread radius or blur radius. CSS understands the value is a color and not a length value.

You can set the color without setting the spread radius or blur radius. CSS understands the value is a color and not a length value.

Example:

例:

img {  filter: drop-shadow(10px 10px 5px orange);}img {  filter: drop-shadow(10px 10px orange);}img {  filter: drop-shadow(10px 10px 5px 5px #333);}

grayscale() (grayscale())

Makes the element have a gray color.

Makes the element have a gray color.

You pass one value from 0 to 1, or from 0% to 100%, where 1 and 100% mean completely gray, and 0 or 0% mean the image is not touched, and the original colors remain.

You pass one value from 0 to 1, or from 0% to 100%, where 1 and 100% mean completely gray, and 0 or 0% mean the image is not touched, and the original colors remain.

Example:

例:

img {  filter: grayscale(50%);}

sepia() (sepia())

Makes the element have a sepia color.

Makes the element have a sepia color.

You pass one value from 0 to 1, or from 0% to 100%, where 1 and 100% mean completely sepia, and 0 or 0% mean the image is not touched, and the original colors remain.

You pass one value from 0 to 1, or from 0% to 100%, where 1 and 100% mean completely sepia, and 0 or 0% mean the image is not touched, and the original colors remain.

Example:

例:

img {  filter: sepia(50%);}

invert() (invert())

Invert the colors of an element. Inverting a color means looking up the opposite of a color in the HSL color wheel. Just search “color wheel” in Google if you have no idea what that means. For example, the opposite of yellow is blue, the opposite of red is cyan. Every single color has an opposite.

Invert the colors of an element. Inverting a color means looking up the opposite of a color in the HSL color wheel. Just search “color wheel” in Google if you have no idea what that means. For example, the opposite of yellow is blue, the opposite of red is cyan. Every single color has an opposite.

You pass a number, from 0 to 1 or from 0% to 100%, that determines the amount of inversion. 1 or 100% means full inversion, 0 or 0% means no inversion.

You pass a number, from 0 to 1 or from 0% to 100%, that determines the amount of inversion. 1 or 100% means full inversion, 0 or 0% means no inversion.

0.5 or 50% will always render a 50% gray color, because you always end up in the middle of the wheel.

0.5 or 50% will always render a 50% gray color, because you always end up in the middle of the wheel.

Example:

例:

img {  filter: invert(50%);}

hue-rotate() (hue-rotate())

The HSL color wheel is represented in degrees. Using hue-rotate() you can rotate the color using a positive or negative rotation.

The HSL color wheel is represented in degrees. Using hue-rotate() you can rotate the color using a positive or negative rotation.

The function accepts a deg value.

The function accepts a deg value.

Example:

例:

img {  filter: hue-rotate(90deg);}

brightness() (brightness())

Alters the brightness of an element.

Alters the brightness of an element.

0 or 0% gives a total black element. 1 or 100% gives an unchanged image.

0 or 0% gives a total black element. 1 or 100% gives an unchanged image.

Values higher than 1 or 100% make the image brighter up to reaching a total white element.

Values higher than 1 or 100% make the image brighter up to reaching a total white element.

Example:

例:

img {  filter: brightness(50%);}

contrast() (contrast())

Alters the contrast of an element.

Alters the contrast of an element.

0 or 0% gives a total gray element. 1 or 100% gives an unchanged image.

0 or 0% gives a total gray element. 1 or 100% gives an unchanged image.

Values higher than 1 or 100% give more contrast.

Values higher than 1 or 100% give more contrast.

Example:

例:

img {  filter: contrast(150%);}

saturate() (saturate())

Alters the saturation of an element.

Alters the saturation of an element.

0 or 0% gives a total grayscale element (with less saturation). 1 or 100% gives an unchanged image.

0 or 0% gives a total grayscale element (with less saturation). 1 or 100% gives an unchanged image.

Values higher than 1 or 100% give more saturation.

Values higher than 1 or 100% give more saturation.

Example:

例:

img {  filter: saturate();}

url() (url())

This filter allows to apply a filter defined in an SVG file. You point to the SVG file location.

This filter allows to apply a filter defined in an SVG file. You point to the SVG file location.

Example:

例:

img {  filter: url(filter.svg);}

SVG filters are out of the scope of this piece, but you can read more on this Smashing Magazine post:

SVG filters are out of the scope of this piece, but you can read more on this Smashing Magazine post:

TRANSFORMS (TRANSFORMS)

Transforms allow you to translate, rotate, scale, and skew elements, in the 2D or 3D space. They are a very cool CSS feature, especially when combined with animations.

Transforms allow you to translate, rotate, scale, and skew elements, in the 2D or 3D space. They are a very cool CSS feature, especially when combined with animations.

2D transforms (2D transforms)

The transform property accepts those functions:

The transform property accepts those functions:

  • translate() to move elements around

    translate() to move elements around

  • rotate() to rotate elements

    rotate() to rotate elements

  • scale() to scale elements in size

    scale() to scale elements in size

  • skew() to twist or slant an element

    skew() to twist or slant an element

  • matrix() a way to perform any of the above operations using a matrix of 6 elements, a less user friendly syntax but less verbose

    matrix() a way to perform any of the above operations using a matrix of 6 elements, a less user friendly syntax but less verbose

We also have axis-specific functions:

We also have axis-specific functions:

  • translateX() to move elements around on the X axis

    translateX() to move elements around on the X axis

  • translateY() to move elements around on the Y axis

    translateY() to move elements around on the Y axis

  • scaleX() to scale elements in size on the X axis

    scaleX() to scale elements in size on the X axis

  • scaleY() to scale elements in size on the Y axis

    scaleY() to scale elements in size on the Y axis

  • skewX() to twist or slant an element on the X axis

    skewX() to twist or slant an element on the X axis

  • skewY() to twist or slant an element on the Y axis

    skewY() to twist or slant an element on the Y axis

Here is an example of a transform which changes the .box element width by 2 (duplicating it) and the height by 0.5 (reducing it to half):

Here is an example of a transform which changes the .box element width by 2 (duplicating it) and the height by 0.5 (reducing it to half):

.box {    transform: scale(2, 0.5);}

lets us set the origin (the (0, 0) coordinates) for the transformation, letting us change the rotation center.

lets us set the origin (the (0, 0) coordinates) for the transformation, letting us change the rotation center.

Combining multiple transforms (Combining multiple transforms)

You can combine multiple transforms by separating each function with a space.

You can combine multiple transforms by separating each function with a space.

For example:

例如:

transform: rotateY(20deg) scaleX(3) translateY(100px);

3D transforms (3D transforms)

We can go one step further and move our elements in a 3D space instead of in a 2D space. With 3D, we are adding another axis, Z, which adds depth to our visuals.

We can go one step further and move our elements in a 3D space instead of in a 2D space. With 3D, we are adding another axis, Z, which adds depth to our visuals.

Using the perspective property you can specify how far the 3D object is from the viewer.

Using the perspective property you can specify how far the 3D object is from the viewer.

Example:

例:

.3Delement {  perspective: 100px;}

perspective-origin determines the appearance of the position of the viewer, how are we looking at it in the X and Y axis.

perspective-origin determines the appearance of the position of the viewer, how are we looking at it in the X and Y axis.

Now we can use additional functions that control the Z axis, and that add up to the other X and Y axis transforms:

Now we can use additional functions that control the Z axis, and that add up to the other X and Y axis transforms:

  • translateZ()

    translateZ()

  • rotateZ()

    rotateZ()

  • scaleZ()

    scaleZ()

and the corresponding shorthands translate3d(), rotate3d() and scale3d() as shorthands for using the translateX(), translateY() and translateZ() functions and so on.

and the corresponding shorthands translate3d() , rotate3d() and scale3d() as shorthands for using the translateX() , translateY() and translateZ() functions and so on.

3D transforms are a bit too advanced for this handbook, but are a great topic to explore on your own.

3D transforms are a bit too advanced for this handbook, but are a great topic to explore on your own.

TRANSITIONS (TRANSITIONS)

CSS Transitions are the simplest way to create an animation in CSS.

CSS Transitions are the simplest way to create an animation in CSS.

In a transition, you change the value of a property, and you tell CSS to slowly change it according to some parameters, towards a final state.

In a transition, you change the value of a property, and you tell CSS to slowly change it according to some parameters, towards a final state.

CSS Transitions are defined by these properties:

CSS Transitions are defined by these properties:

The transition property is a handy shorthand:

The transition property is a handy shorthand:

.container {  transition: property              duration              timing-function              delay;}

Example of a CSS Transition (Example of a CSS Transition)

This code implements a CSS Transition:

This code implements a CSS Transition:

.one,.three {  background: rgba(142, 92, 205, .75);  transition: background 1s ease-in;}.two,.four {  background: rgba(236, 252, 100, .75);}.circle:hover {  background: rgba(142, 92, 205, .25); /* lighter */}

See the example on Glitch

See the example on Glitch

When hovering the .one and .three elements, the purple circles, there is a transition animation that eases the change of background, while the yellow circles do not, because they do not have the transition property defined.

When hovering the .one and .three elements, the purple circles, there is a transition animation that eases the change of background, while the yellow circles do not, because they do not have the transition property defined.

Transition timing function values (Transition timing function values)

transition-timing-function allows you to specify the acceleration curve of the transition.

transition-timing-function allows you to specify the acceleration curve of the transition.

There are some simple values you can use:

There are some simple values you can use:

  • linear

    linear

  • ease

    ease

  • ease-in

    ease-in

  • ease-out

    ease-out

  • ease-in-out

    ease-in-out

shows how these work in practice.

shows how these work in practice.

You can create a completely custom timing function using . This is rather advanced, but basically any of those functions above are built using bezier curves. We have handy names as they are common ones.

You can create a completely custom timing function using . This is rather advanced, but basically any of those functions above are built using bezier curves. We have handy names as they are common ones.

CSS Transitions in Browser DevTools (CSS Transitions in Browser DevTools)

The offer a great way to visualize transitions.

The offer a great way to visualize transitions.

This is Chrome:

This is Chrome:

This is Firefox:

This is Firefox:

From those panels you can live edit the transition and experiment in the page directly without reloading your code.

From those panels you can live edit the transition and experiment in the page directly without reloading your code.

Which Properties you can Animate using CSS Animations (Which Properties you can Animate using CSS Animations)

A lot! They are the same you can animate using CSS Transitions, too.

A lot! They are the same you can animate using CSS Transitions, too.

Here’s the full list:

这是完整列表:

  • background

    background

  • background-color

    background-color

  • background-position

    background-position

  • background-size

    background-size

  • border

    border

  • border-color

    border-color

  • border-width

    border-width

  • border-bottom

    border-bottom

  • border-bottom-color

    border-bottom-color

  • border-bottom-left-radius

    border-bottom-left-radius

  • border-bottom-right-radius

    border-bottom-right-radius

  • border-bottom-width

    border-bottom-width

  • border-left

    border-left

  • border-left-color

    border-left-color

  • border-left-width

    border-left-width

  • border-radius

    border-radius

  • border-right

    border-right

  • border-right-color

    border-right-color

  • border-right-width

    border-right-width

  • border-spacing

    border-spacing

  • border-top

    border-top

  • border-top-color

    border-top-color

  • border-top-left-radius

    border-top-left-radius

  • border-top-right-radius

    border-top-right-radius

  • border-top-width

    border-top-width

  • bottom

    bottom

  • box-shadow

    box-shadow

  • caret-color

    caret-color

  • clip

    clip

  • color

    color

  • column-count

    column-count

  • column-gap

    column-gap

  • column-rule

    column-rule

  • column-rule-color

    column-rule-color

  • column-rule-width

    column-rule-width

  • column-width

    column-width

  • columns

    columns

  • content

    content

  • filter

    filter

  • flex

    flex

  • flex-basis

    flex-basis

  • flex-grow

    flex-grow

  • flex-shrink

    flex-shrink

  • font

    font

  • font-size

    font-size

  • font-size-adjust

    font-size-adjust

  • font-stretch

    font-stretch

  • font-weight

    font-weight

  • grid-area

    grid-area

  • grid-auto-columns

    grid-auto-columns

  • grid-auto-flow

    grid-auto-flow

  • grid-auto-rows

    grid-auto-rows

  • grid-column-end

    grid-column-end

  • grid-column-gap

    grid-column-gap

  • grid-column-start

    grid-column-start

  • grid-column

    grid-column

  • grid-gap

    grid-gap

  • grid-row-end

    grid-row-end

  • grid-row-gap

    grid-row-gap

  • grid-row-start

    grid-row-start

  • grid-row

    grid-row

  • grid-template-areas

    grid-template-areas

  • grid-template-columns

    grid-template-columns

  • grid-template-rows

    grid-template-rows

  • grid-template

    grid-template

  • grid

    grid

  • height

    height

  • left

    left

  • letter-spacing

    letter-spacing

  • line-height

    line-height

  • margin

    margin

  • margin-bottom

    margin-bottom

  • margin-left

    margin-left

  • margin-right

    margin-right

  • margin-top

    margin-top

  • max-height

    max-height

  • max-width

    max-width

  • min-height

    min-height

  • min-width

    min-width

  • opacity

    opacity

  • order

    order

  • outline

    outline

  • outline-color

    outline-color

  • outline-offset

    outline-offset

  • outline-width

    outline-width

  • padding

    padding

  • padding-bottom

    padding-bottom

  • padding-left

    padding-left

  • padding-right

    padding-right

  • padding-top

    padding-top

  • perspective

    perspective

  • perspective-origin

    perspective-origin

  • quotes

    quotes

  • right

    right

  • tab-size

    tab-size

  • text-decoration

    text-decoration

  • text-decoration-color

    text-decoration-color

  • text-indent

    text-indent

  • text-shadow

    text-shadow

  • top

    top

  • transform.

    transform.

  • vertical-align

    vertical-align

  • visibility

    visibility

  • width

    width

  • word-spacing

    word-spacing

  • z-index

    z-index

ANIMATIONS (ANIMATIONS)

CSS Animations are a great way to create visual animations, not limited to a single movement like CSS Transitions, but much more articulated.

CSS Animations are a great way to create visual animations, not limited to a single movement like CSS Transitions, but much more articulated.

An animation is applied to an element using the animation property.

使用animation属性将动画应用于元素。

.container {  animation: spin 10s linear infinite;}

spin is the name of the animation, which we need to define separately. We also tell CSS to make the animation last 10 seconds, perform it in a linear way (no acceleration or any difference in its speed) and to repeat it infinitely.

spin是动画的名称,我们需要单独定义它。 We also tell CSS to make the animation last 10 seconds, perform it in a linear way (no acceleration or any difference in its speed) and to repeat it infinitely.

You must define how your animation works using keyframes. Example of an animation that rotates an item:

您必须使用关键帧 定义动画的工作方式 。 Example of an animation that rotates an item:

@keyframes spin {  0% {    transform: rotateZ(0);  }  100% {    transform: rotateZ(360deg);  }}

Inside the @keyframes definition you can have as many intermediate waypoints as you want.

@keyframes定义中,您可以根据需要设置@keyframes多个中间航路点。

In this case we instruct CSS to make the transform property to rotate the Z axis from 0 to 360 grades, completing the full loop.

In this case we instruct CSS to make the transform property to rotate the Z axis from 0 to 360 grades, completing the full loop.

You can use any CSS transform here.

您可以在此处使用任何CSS转换。

Notice how this does not dictate anything about the temporal interval the animation should take. This is defined when you use it via animation.

请注意,这如何不决定动画应采用的时间间隔。 通过animation使用时定义。

CSS动画示例 (A CSS Animations Example)

I want to draw four circles, all with a starting point in common, all 90 degrees distant from each other.

我想绘制四个圆,它们的起点都相同,并且彼此相距90度。

body { display: grid; place-items: center; height: 100vh;}.circle { border-radius: 50%; left: calc(50% - 6.25em); top: calc(50% - 12.5em); transform-origin: 50% 12.5em; width: 12.5em; height: 12.5em; position: absolute; box-shadow: 0 1em 2em rgba(0, 0, 0, .5);}.one,.three { background: rgba(142, 92, 205, .75);}.two,.four { background: rgba(236, 252, 100, .75);}.one { transform: rotateZ(0);}.two { transform: rotateZ(90deg);}.three { transform: rotateZ(180deg);}.four { transform: rotateZ(-90deg);}

You can see them in this Glitch:

You can see them in this Glitch:

Let’s make this structure (all the circles together) rotate. To do this, we apply an animation on the container, and we define that animation as a 360 degree rotation:

让我们旋转该结构(所有圆一起)。 To do this, we apply an animation on the container, and we define that animation as a 360 degree rotation:

@keyframes spin {  0% {    transform: rotateZ(0);  }  100% {    transform: rotateZ(360deg);  }}.container {  animation: spin 10s linear infinite;}

See it on

See it on

You can add more keyframes to have funnier animations:

您可以添加更多关键帧来制作更有趣的动画:

@keyframes spin {  0% {    transform: rotateZ(0);  }  25% {    transform: rotateZ(30deg);  }  50% {    transform: rotateZ(270deg);  }  75% {    transform: rotateZ(180deg);  }  100% {    transform: rotateZ(360deg);  }}

See the example on

See the example on

CSS动画属性 (The CSS animation properties)

CSS animations offers a lot of different parameters you can tweak:

CSS动画提供了许多可以调整的不同参数:

The animation property is a shorthand for all these properties, in this order:

animation属性是所有这些属性的简写,顺序如下:

.container {  animation: name             duration             timing-function             delay             iteration-count             direction             fill-mode             play-state;}

This is the example we used above:

这是我们上面使用的示例:

.container {  animation: spin 10s linear infinite;}

CSS动画JavaScript事件 (JavaScript events for CSS Animations)

Using JavaScript you can listen for the following events:

Using JavaScript you can listen for the following events:

  • animationstart

    animationstart

  • animationend

    animationend

  • animationiteration

    animationiteration

Be careful with animationstart, because if the animation starts on page load, your JavaScript code is always executed after the CSS has been processed, so the animation is already started and you cannot intercept the event.

Be careful with animationstart , because if the animation starts on page load, your JavaScript code is always executed after the CSS has been processed, so the animation is already started and you cannot intercept the event.

const container = document.querySelector('.container')container.addEventListener('animationstart', (e) => {  //do something}, false)container.addEventListener('animationend', (e) => {  //do something}, false)container.addEventListener('animationiteration', (e) => {  //do something}, false)

Which Properties You Can Animate using CSS Animations (Which Properties You Can Animate using CSS Animations)

A lot! They are the same you can animate using CSS Transitions, too.

A lot! They are the same you can animate using CSS Transitions, too.

Here’s the full list:

这是完整列表:

  • background

    background

  • background-color

    background-color

  • background-position

    background-position

  • background-size

    background-size

  • border

    border

  • border-color

    border-color

  • border-width

    border-width

  • border-bottom

    border-bottom

  • border-bottom-color

    border-bottom-color

  • border-bottom-left-radius

    border-bottom-left-radius

  • border-bottom-right-radius

    border-bottom-right-radius

  • border-bottom-width

    border-bottom-width

  • border-left

    border-left

  • border-left-color

    border-left-color

  • border-left-width

    border-left-width

  • border-radius

    border-radius

  • border-right

    border-right

  • border-right-color

    border-right-color

  • border-right-width

    border-right-width

  • border-spacing

    border-spacing

  • border-top

    border-top

  • border-top-color

    border-top-color

  • border-top-left-radius

    border-top-left-radius

  • border-top-right-radius

    border-top-right-radius

  • border-top-width

    border-top-width

  • bottom

    bottom

  • box-shadow

    box-shadow

  • caret-color

    caret-color

  • clip

    clip

  • color

    color

  • column-count

    column-count

  • column-gap

    column-gap

  • column-rule

    column-rule

  • column-rule-color

    column-rule-color

  • column-rule-width

    column-rule-width

  • column-width

    column-width

  • columns

    columns

  • content

    content

  • filter

    filter

  • flex

    flex

  • flex-basis

    flex-basis

  • flex-grow

    flex-grow

  • flex-shrink

    flex-shrink

  • font

    font

  • font-size

    font-size

  • font-size-adjust

    font-size-adjust

  • font-stretch

    font-stretch

  • font-weight

    font-weight

  • grid-area

    grid-area

  • grid-auto-columns

    grid-auto-columns

  • grid-auto-flow

    grid-auto-flow

  • grid-auto-rows

    grid-auto-rows

  • grid-column-end

    grid-column-end

  • grid-column-gap

    grid-column-gap

  • grid-column-start

    grid-column-start

  • grid-column

    grid-column

  • grid-gap

    grid-gap

  • grid-row-end

    grid-row-end

  • grid-row-gap

    grid-row-gap

  • grid-row-start

    grid-row-start

  • grid-row

    grid-row

  • grid-template-areas

    grid-template-areas

  • grid-template-columns

    grid-template-columns

  • grid-template-rows

    grid-template-rows

  • grid-template

    grid-template

  • grid

    grid

  • height

    height

  • left

    left

  • letter-spacing

    letter-spacing

  • line-height

    line-height

  • margin

    margin

  • margin-bottom

    margin-bottom

  • margin-left

    margin-left

  • margin-right

    margin-right

  • margin-top

    margin-top

  • max-height

    max-height

  • max-width

    max-width

  • min-height

    min-height

  • min-width

    min-width

  • opacity

    opacity

  • order

    order

  • outline

    outline

  • outline-color

    outline-color

  • outline-offset

    outline-offset

  • outline-width

    outline-width

  • padding

    padding

  • padding-bottom

    padding-bottom

  • padding-left

    padding-left

  • padding-right

    padding-right

  • padding-top

    padding-top

  • perspective

    perspective

  • perspective-origin

    perspective-origin

  • quotes

    quotes

  • right

    right

  • tab-size

    tab-size

  • text-decoration

    text-decoration

  • text-decoration-color

    text-decoration-color

  • text-indent

    text-indent

  • text-shadow

    text-shadow

  • top

    top

  • transform.

    transform.

  • vertical-align

    vertical-align

  • visibility

    visibility

  • width

    width

  • word-spacing

    word-spacing

  • z-index

    z-index

NORMALIZING CSS (NORMALIZING CSS)

The default browser stylesheet is the set of rules that browsers have to apply to give some minimum style to elements.

The default browser stylesheet is the set of rules that browsers have to apply to give some minimum style to elements.

Most of the time those styles are very useful.

Most of the time those styles are very useful.

Since every browser has its own set, it’s common to find a common ground.

Since every browser has its own set, it's common to find a common ground.

Rather than removing all defaults, like one of the CSS reset approaches does, the normalizing process removes browser inconsistencies, while keeping a basic set of rules you can rely on.

Rather than removing all defaults, like one of the CSS reset approaches does, the normalizing process removes browser inconsistencies, while keeping a basic set of rules you can rely on.

Normalize.css is the most commonly used solution for this problem.

Normalize.css is the most commonly used solution for this problem.

You must load the normalizing CSS file before any other CSS.

You must load the normalizing CSS file before any other CSS.

ERROR HANDLING (ERROR HANDLING)

CSS is resilient. When it finds an error, it does not act like JavaScript which packs up all its things and goes away altogether, terminating all the script executions after the error is found.

CSS is resilient. When it finds an error, it does not act like JavaScript which packs up all its things and goes away altogether, terminating all the script executions after the error is found.

CSS tries very hard to do what you want.

CSS tries very hard to do what you want.

If a line has an error, it skips it and jumps to the next line without any error.

If a line has an error, it skips it and jumps to the next line without any error.

If you forget the semicolon on one line:

If you forget the semicolon on one line:

p {  font-size: 20px  color: black;  border: 1px solid black;}

the line with the error AND the next one will not be applied, but the third rule will be successfully applied on the page. Basically, it scans all until it finds a semicolon, but when it reaches it, the rule is now font-size: 20px color: black;, which is invalid, so it skips it.

the line with the error AND the next one will not be applied, but the third rule will be successfully applied on the page. Basically, it scans all until it finds a semicolon, but when it reaches it, the rule is now font-size: 20px color: black; , which is invalid, so it skips it.

Sometimes it’s tricky to realize there is an error somewhere, and where that error is, because the browser won’t tell us.

Sometimes it's tricky to realize there is an error somewhere, and where that error is, because the browser won't tell us.

This is why tools like exist.

This is why tools like exist.

VENDOR PREFIXES (VENDOR PREFIXES)

Vendor prefixes are one way browsers use to give CSS developers access to newer features not yet considered stable.

Vendor prefixes are one way browsers use to give CSS developers access to newer features not yet considered stable.

Before going on, keep in mind that this approach is declining in popularity. People now favour using experimental flags, which must be enabled explicitly in the user’s browser.

Before going on, keep in mind that this approach is declining in popularity. People now favour using experimental flags , which must be enabled explicitly in the user's browser.

Why? Because developers, instead of considering vendor prefixes as a way to preview features, sometimes ship them in production — something considered harmful by the CSS Working Group.

为什么? Because developers, instead of considering vendor prefixes as a way to preview features, sometimes ship them in production — something considered harmful by the CSS Working Group.

Mostly because once you add a flag and developers start using it in production, browsers are in a bad position if they realise something must change. With flags, you can’t ship a feature unless you can push all your visitors to enable that flag in their browser (just joking, don’t try).

Mostly because once you add a flag and developers start using it in production, browsers are in a bad position if they realise something must change. With flags, you can't ship a feature unless you can push all your visitors to enable that flag in their browser (just joking, don't try).

That said, let’s see what vendor prefixes are.

That said, let's see what vendor prefixes are.

I specifically remember them for working with CSS Transitions in the past. Instead of just using the transition property, you had to do this:

I specifically remember them for working with CSS Transitions in the past. Instead of just using the transition property, you had to do this:

.myClass {    -webkit-transition: all 1s linear;    -moz-transition: all 1s linear;    -ms-transition: all 1s linear;    -o-transition: all 1s linear;    transition: all 1s linear;}

Now you just use

Now you just use

.myClass {    transition: all 1s linear;}

since the property is now well supported by all modern browsers.

since the property is now well supported by all modern browsers.

The prefixes used are:

The prefixes used are:

  • -webkit- (Chrome, Safari, iOS Safari / iOS WebView, Android)

    -webkit- (Chrome, Safari, iOS Safari / iOS WebView, Android)

  • -moz- (Safari)

    -moz- (Safari)

  • -ms- (Edge, Internet Explorer)

    -ms- (Edge, Internet Explorer)

  • -o- (Opera, Opera Mini)

    -o- (Opera, Opera Mini)

Since Opera is Chromium-based and Edge will soon be too, -o- and -ms- will probably soon go out of fashion. But as we said, vendor prefixes as a whole are going out of fashion, too.

Since Opera is Chromium-based and Edge will soon be too, -o- and -ms- will probably soon go out of fashion. But as we said, vendor prefixes as a whole are going out of fashion, too.

Writing prefixes is hard, mostly because of uncertainty. Do you actually need a prefix for one property? Several online resources are outdated, too, which makes it even harder to do right. Projects like can automate the process in its entirety without us needing to find out if a prefix is needed any more, or the feature is now stable and the prefix should be dropped. It uses data from caniuse.com, a very good reference site for all things related to browser support.

Writing prefixes is hard, mostly because of uncertainty. Do you actually need a prefix for one property? Several online resources are outdated, too, which makes it even harder to do right. Projects like can automate the process in its entirety without us needing to find out if a prefix is needed any more, or the feature is now stable and the prefix should be dropped. It uses data from caniuse.com, a very good reference site for all things related to browser support.

If you use React or Vue, projects like create-react-app and Vue CLI, two common ways to start building an application, use autoprefixer out of the box, so you don't even have to worry about it.

If you use React or Vue, projects like create-react-app and Vue CLI, two common ways to start building an application, use autoprefixer out of the box, so you don't even have to worry about it.

CSS FOR PRINT (CSS FOR PRINT)

Even though we increasingly stare at our screens, printing is still a thing.

Even though we increasingly stare at our screens, printing is still a thing.

Even with blog posts. I remember one time back in 2009 I met a person that told me he made his personal assistant print every blog post I published (yes, I stared blankly for a little bit). Definitely unexpected.

Even with blog posts. I remember one time back in 2009 I met a person that told me he made his personal assistant print every blog post I published (yes, I stared blankly for a little bit). Definitely unexpected.

My main use case for looking into printing usually is printing to a PDF. I might create something inside the browser, and I want to make it available as PDF.

My main use case for looking into printing usually is printing to a PDF. I might create something inside the browser, and I want to make it available as PDF.

Browsers make this very easy, with Chrome defaulting to “Save” when trying to print a document and a printer is not available, and Safari has a dedicated button in the menu bar:

Browsers make this very easy, with Chrome defaulting to “Save” when trying to print a document and a printer is not available, and Safari has a dedicated button in the menu bar:

Some common things you might want to do when printing is to hide some parts of the document, maybe the footer, something in the header, the sidebar.

Some common things you might want to do when printing is to hide some parts of the document, maybe the footer, something in the header, the sidebar.

Maybe you want to use a different font for printing, which is totally legit.

Maybe you want to use a different font for printing, which is totally legit.

If you have a large CSS for print, you’d better use a separate file for it. Browsers will only download it when printing:

If you have a large CSS for print, you'd better use a separate file for it. Browsers will only download it when printing:

CSS @media print (CSS @media print)

An alternative to the previous approach is media queries. Anything you add inside this block:

An alternative to the previous approach is media queries. Anything you add inside this block:

@media print {  /* ... */}

is going to be applied only to printed documents.

is going to be applied only to printed documents.

HTML is great because of links. It’s called HyperText for a good reason. When printing we might lose a lot of information, depending on the content.

HTML is great because of links. It's called HyperText for a good reason. When printing we might lose a lot of information, depending on the content.

CSS offers a great way to solve this problem by editing the content, appending the link after the <;a> tag text, using:

CSS offers a great way to solve this problem by editing the content, appending the link after the < ;a> tag text, using:

@media print {    a[href*='//']:after {        content:" (" attr(href) ") ";        color: $primary;    }}

I target a[href*='//'] to only do this for external links. I might have internal links for navigation and internal indexing purposes, which would be useless in most of my use cases. If you also want internal links to be printed, just do:

I target a[href*='//'] to only do this for external links. I might have internal links for navigation and internal indexing purposes, which would be useless in most of my use cases. If you also want internal links to be printed, just do:

@media print {    a:after {        content:" (" attr(href) ") ";        color: $primary;    }}

Page margins (Page margins)

You can add margins to every single page. cm or in is a good unit for paper printing.

You can add margins to every single page. cm or in is a good unit for paper printing.

@page {    margin-top: 2cm;    margin-bottom: 2cm;    margin-left: 2cm;    margin-right: 2cm;}

@page can also be used to only target the first page, using @page :first, or only the left and right pages using @page :left and @page: right.

@page can also be used to only target the first page, using @page :first , or only the left and right pages using @page :left and @page: right .

Page breaks (Page breaks)

You might want to add a page break after some elements, or before them. Use page-break-after and page-break-before:

You might want to add a page break after some elements, or before them. Use page-break-after and page-break-before :

.book-date {    page-break-after: always;}.post-content {    page-break-before: always;}

Those properties .

Those properties .

Avoid breaking images in the middle (Avoid breaking images in the middle)

I experienced this with Firefox: images by default are cut in the middle, and continue on the next page. It might also happen to text.

I experienced this with Firefox: images by default are cut in the middle, and continue on the next page. It might also happen to text.

Use

p {  page-break-inside: avoid;}

and wrap your images in a p tag. Targeting img directly didn't work in my tests.

and wrap your images in a p tag. Targeting img directly didn't work in my tests.

This applies to other content as well, not just images. If you notice something is cut when you don’t want, use this property.

This applies to other content as well, not just images. If you notice something is cut when you don't want, use this property.

Debug the printing presentation (Debug the printing presentation)

The Chrome DevTools offer ways to emulate the print layout:

The Chrome DevTools offer ways to emulate the print layout:

Once the panel opens, change the rendering emulation to print:

Once the panel opens, change the rendering emulation to print :

WRAPPING UP (WRAPPING UP)

I hope this article helped you get up to speed with CSS and get an overview of the main features you can use to style your pages and apps. I wrote it 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, and I hope I achieved with this goal.

I hope this article helped you get up to speed with CSS and get an overview of the main features you can use to style your pages and apps. I wrote it 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, and I hope I achieved with this goal.

Flavio

弗拉维奥

翻译自:

css参考手册css3手册

转载地址:http://lcwzd.baihongyu.com/

你可能感兴趣的文章
session和cookie
查看>>
tftp 开发板ping不通PC机
查看>>
未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”
查看>>
Erdos
查看>>
docker初学
查看>>
面向对象的程序第三次实验作业
查看>>
Windows 安装启动apache时出现错误的解决方法
查看>>
Object.prototype.toString()
查看>>
int.Parse()与int.TryParse()
查看>>
c#调用钩子
查看>>
最近最少使用队列算法
查看>>
ONOS:负载均衡路由算法及应用开发(二)
查看>>
把js写到链接a标签的href中和写到onclick中的区别
查看>>
压缩解压缩命令
查看>>
MySQL基于binlog主从复制
查看>>
HDU 1394(归并求逆序对)
查看>>
配置 Windows 下的 nodejs C++ 模块编译环境 安装 node-gyp
查看>>
我和Socket的第一次亲密接触
查看>>
2016/09/22
查看>>
2016/09/02
查看>>