CSS Volume 2

CSS Volume 2

版权声明:署名-非商业性使用-相同方式共享

CSS Combinators

@@ Tags: 关系选择器;组合选择器
@@ Refer: https://www.w3schools.com/css/css_combinators.asp

A combinator(组合) is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

  • ' ' descendant selector (后裔选择器)
    • The descendant selector matches all elements that are descendants of a specified element.
    • The following example selects all <p> elements inside <div> elements:
    • div p { background-color: yellow; }
  • '>' child selector (子选择器)
    • The child selector selects all elements that are the children of a specified element.
    • The following example selects all <p> elements that are children of a <div> element:
    • div > p { background-color: yellow; }
  • '+' adjacent sibling selector (相邻兄弟选择器)
    • The adjacent sibling selector is used to select an element that is directly after another specific element(直接选择跟在另一个指定元素后的元素).
    • Sibling elements must have the same parent element, and "adjacent" means "immediately following(紧跟着)".
    • The following example selects the first <p> element that are placed immediately after <div> elements:
    • div + p { background-color: yellow; }
  • '~' general sibling selector (一般同级选择器)
    • The general sibling selector selects all elements that are next siblings of a specified element.
    • The following example selects all <p> elements that are next siblings of <div> elements:
    • div ~ p { background-color: yellow; }

NOTE

组合选择器结合伪类 可以在元素状态改变时, 修改另一个元素的状态

p {
  display: none;
  background-color: yellow;
  padding: 20px;
}

div:hover p {
  display: block;
}

Try it

CSS Pseudo-classes

@@ Tags: 伪类

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus
selector:pseudo-class {
  property: value;
}

/* unvisited link */
a:link {
  color: #FF0000;
}

/* visited link */
a:visited {
  color: #00FF00;
}

/* mouse over link */
a:hover {
  color: #FF00FF;
}

/* selected link */
a:active {
  color: #0000FF;
}

/* Pseudo-classes can be combined with HTML classes */
a.highlight:hover {
  color: #ff0000;
}

NOTE

a:hover MUST come after(紧跟) a:link and a:visited in the CSS definition in order to be effective!
a:active MUST come after a:hover in the CSS definition in order to be effective! Pseudo-class names are not case-sensitive.

CSS - The :first-child Pseudo-class

The :first-child pseudo-class matches a specified element that is the first child of another element.

p:first-child {
  color: blue;
}

p i:first-child {
  color: blue;
}

p:first-child i {
  color: blue;
}

CSS - The :lang Pseudo-class

The :lang pseudo-class allows you to define special rules for different languages.

<html>
  <head>
    <style>
    q:lang(no) {
      quotes: "~" "~";
    }
    </style>
  </head>
  <body>
    <p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>
  </body>
</html>

All CSS Pseudo Classes

Selector Example Example description
:active a:active Selects the active link
:checked input:checked Selects every checked <input> element
:disabled input:disabled Selects every disabled <input> element
:empty p:empty Selects every <p> element that has no children
:enabled input:enabled Selects every enabled <input> element
:first-child p:first-child Selects every <p> elements that is the first child of its parent
:first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent
:focus input:focus Selects the <input> element that has focus
:hover a:hover Selects links on mouse over
:in-range input:in-range Selects <input> elements with a value within a specified range
:invalid input:invalid Selects all <input> elements with an invalid value
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"
:last-child p:last-child Selects every <p> elements that is the last child of its parent
:last-of-type p:last-of-type Selects every <p> element that is the last <p> element of its parent
:link a:link Selects all unvisited links
:not(selector) :not(p) Selects every element that is not a <p> element
:nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent
:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the second <p> element of its parent
:only-of-type p:only-of-type Selects every <p> element that is the only <p> element of its parent
:only-child p:only-child Selects every <p> element that is the only child of its parent
:optional input:optional Selects <input> elements with no "required" attribute
:out-of-range input:out-of-range Selects <input> elements with a value outside a specified range
:read-only input:read-only Selects <input> elements with a "readonly" attribute specified
:read-write input:read-write Selects <input> elements with no "readonly" attribute
:required input:required Selects <input> elements with a "required" attribute specified
:root root Selects the document's root element
:target #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
:valid input:valid Selects all <input> elements with a valid value
:visited a:visited Selects all visited links

CSS Pseudo-elements

@@ Tags: 伪元素
@@ Refer: https://www.w3schools.com/css/css_pseudo_elements.asp

A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

  • Style the first letter, or line, of an element
  • Insert content before, or after, the content of an element
selector::pseudo-element {
  property: value;
}

/* Pseudo-elements can be combined with HTML classes:  */
p.intro::first-letter {
  color: #ff0000;
  font-size: 200%;
}

/* Several pseudo-elements can also be combined. */
p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

p::first-line {
  color: #0000ff;
  font-variant: small-caps;
}

The ::first-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first line of a text.

p::first-line {
  color: #ff0000;
  font-variant: small-caps;
}

Note: The ::first-line pseudo-element can only be applied to block-level elements.
Notice the double colon notation - ::first-line versus :first-line

The double colon replaced the single-colon notation for pseudo-elements in CSS3. This was an attempt from W3C to distinguish between pseudo-classes and pseudo-elements.

The single-colon syntax was used for both pseudo-classes and pseudo-elements in CSS2 and CSS1.

For backward compatibility, the single-colon syntax is acceptable for CSS2 and CSS1 pseudo-elements.

The ::before Pseudo-element

The ::before pseudo-element can be used to insert some content before the content of an element(在元素内容前插入一些内容).

/* 在每个h1标题前插入一个动画 */
h1::before {
  content: url(smiley.gif);
}

content Property: references

The ::marker Pseudo-element

The ::marker pseudo-element selects the markers of list items(列表项的标记).

::marker {
  color: red;
  font-size: 23px;
}

The ::selection Pseudo-element

The ::selection pseudo-element matches the portion of an element that is selected by a user(元素被用户选中的部分).

The following CSS properties can be applied to ::selection: color, background, cursor, and outline.

The following example makes the selected text red on a yellow background:

::selection {
  color: red;
  background: yellow;
}

All CSS Pseudo Elements

Selector Example Example description
::after p::after Insert something after the content of each <p> element
::before p::before Insert something before the content of each <p> element
::first-letter p::first-letter Selects the first letter of each <p> element
::first-line p::first-line Selects the first line of each <p> element
::marker ::marker Selects the markers of list items
::selection p::selection Selects the portion of an element that is selected by a user

CSS Opacity / Transparency

The opacity property specifies the opacity/transparency of an element.

The opacity property can take a value from 0.0 - 1.0.

img {
  opacity: 0.5;
}

CSS Dropdowns

Create a hoverable dropdown(可悬停下拉框) with CSS.

<div class="dropdown">
  <span>Mouse over me</span>
  <div class="dropdown-content">
  <p>Hello World!</p>
  </div>
</div>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}

CSS Image Sprites(图片拼合)

An image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server requests.

Using image sprites will reduce the number of server requests and save bandwidth(带宽).

With CSS, we can show just the part of the image we need.

#home {
  width: 46px;
  height: 44px;
  background: url(img_navsprites.gif) 0 0;
/* 
  上面的简写形式实际上是设置下面两个属性:
    background-image
    background-position
*/
}

CSS Attribute Selectors

@@ Tags: 属性选择器

input[type="text"] {
  width: 150px;
  display: block;
  margin-bottom: 10px;
  background-color: yellow;
}

input[type="button"] {
  width: 120px;
  margin-left: 35px;
  display: block;
}
  • [attribute] - 选择具有目标属性的元素
    • Example: [target]
    • Selects all elements with a target attribute
  • [attribute=value] - 选择属性与值完全匹配上的元素
    • Example: [target=_blank]
    • Selects all elements with target="_blank"
  • [attribute~=value] 选择属性值包含某字的元素(word层次)
    • Example: [title~=flower]
    • Selects all elements with a title attribute containing the word "flower"
  • [attribute*=value] 选择属性值包含某内容的元素(非word层次)
    • Example: a[href*="w3schools"]
    • Selects every <a> element whose href attribute value contains the substring "w3schools"
  • [attribute|=value] 选择属性值匹配或者值跟随(-)的元素
    • Example: [lang|=en] 匹配 <div lan="en-zh"></div>
    • Selects all elements with a lang attribute value starting with "en"
  • [attribute^=value] 选择属性值开头匹配的元素
    • Example: a[href^="https"]
    • Selects every <a> element whose href attribute value begins with "https"
  • [attribute$=value]
    • Example: a[href$=".pdf"] 选择属性值结尾匹配的元素
    • Selects every <a> element whose href attribute value ends with ".pdf"

CSS Counters

@@ Tags: 计数器;自动编号;嵌套计数器

CSS counters are "variables" maintained by CSS whose values can be incremented by CSS rules (to track how many times they are used). Counters let you adjust the appearance of content based on its placement in the document.

Automatic Numbering With Counters

@@ Refer: https://www.w3schools.com/css/tryit.asp?filename=trycss_counters1

To work with CSS counters we will use the following properties:

  • counter-reset - Creates or resets a counter
  • counter-increment - Increments a counter value
  • content - Inserts generated content
  • counter() or counters() function - Adds the value of a counter to an element

To use a CSS counter, it must first be created with counter-reset.

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Nesting Counters

@@ Refer: https://www.w3schools.com/css/tryit.asp?filename=trycss_counters2

body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here we use the counters() function to insert a string between different levels of nested counters:

ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}

Try it Yourself

CSS Units

@@ Tags: CSS单位;CSS像素;点
@@ Refer: https://www.w3schools.com/css/css_units.asp

CSS has several different units for expressing a length.

Many CSS properties take "length" values, such as width, margin, padding, font-size, etc.

Length is a number followed by a length unit, such as 10px, 2em, etc.

There are two types of length units: absolute and relative.

Absolute Lengths

The absolute length units are fixed and a length expressed in any of these will appear as exactly that size.

Absolute length units are not recommended for use on screen, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout.

  • cm centimeters(厘米)
  • mm millimeters(毫米)
  • in inches(英寸)
    1in = 96px = 2.54cm
  • px pixels(像素)
    • 1px = 1/96th of 1in
    • Pixels are relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.
  • pt points(点)
    1pt = 1/72 of 1in
  • pc picas(12点活字)
    1pc = 12 pt

Relative Lengths

Relative length units specify a length relative to another length property. Relative length units scale better between different rendering mediums.

  • em
    Relative to the font-size of the element (2em means 2 times the size of the current font)
  • ex
    Relative to the x-height of the current font (rarely used)
  • ch
    Relative to width of the "0" (zero)
  • rem
    Relative to font-size of the root element
  • vw
    Relative to 1% of the width of the viewport*
  • vh
    Relative to 1% of the height of the viewport*
  • vmin
    Relative to 1% of viewport's* smaller dimension
  • vmax
    Relative to 1% of viewport's* larger dimension
  • %
    Relative to the parent element

Tip: The em and rem units are practical in creating perfectly scalable layout!
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.

CSS Specificity(优先级)

@@ Tags: CSS优先级;CSS权重;权值算法;优先级算法
@@ Refer: https://www.w3schools.com/css/css_specificity.asp

If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element.

<html>
<head>
  <style>
    #demo {color: blue;}
    .test {color: green;}
    p {color: red;}
  </style>
</head>
<body>
  <p id="demo" class="test">Hello World!</p>
</body>
</html>

The text will now be blue, because the id selector is given higher priority.

Specificity Hierarchy(层次结构)

Every CSS selector has its place in the specificity hierarchy.

There are four categories which define the specificity level of a selector:

  • Inline styles
    • Example: <h1 style="color: pink;">
    • Specificity value: 1000
  • IDs
    • Example: #navbar
    • Specificity value: 100
  • Classes, pseudo-classes, attribute selectors
    • Example: .test, :hover, [href]
    • Specificity value: 10
  • Elements and pseudo-elements
    • Example: h1, :before
    • Specificity value: 1

Note: There is one exception to this rule: if you use the !important rule, it will even override inline styles!

How to Calculate Specificity?

  • * -> value: 0
  • p -> value: 1
  • p.test -> value: 11=1+10
  • p#demo -> value: 101=1+100
  • #navbar p#demo -> value: 201=100+1+100

The selector with the highest specificity value will win and take effect!

More Specificity Rules Examples

  • Equal specificity(权值相同)
    If the same rule is written twice into the external style sheet, then the latest rule wins.

  • Contextual selectors are more specific than a single element selector

    From external CSS file:
    #content h1 {background-color: red;}
    
    In HTML file(will be applied):
    <style>
    #content h1 {background-color: yellow;}
    </style>
    
  • ID selectors have a higher specificity than attribute selectors
    ID选择器比属性选择器优先级更高

  • The universal selector (*) and inherited values have a specificity of 0
    通用选择器及继承属性权重为0

CSS The !important Rule

@@ Refer: https://www.w3schools.com/css/css_important.asp

The !important rule in CSS is used to add more importance to a property/value than normal.

In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!

<html>
<head>
<style>
#myid {
  background-color: blue;
}

.myclass {
  background-color: gray;
}

p {
  background-color: red !important;
}
</style>
</head>
<body>
  <p>This is some text in a paragraph.</p>
  <p class="myclass">This is some text in a paragraph.</p>
  <p id="myid">This is some text in a paragraph.</p>
</body>
</html>

CSS Math Functions

The CSS math functions allow mathematical expressions to be used as property values. Here, we will explain the calc(), max() and min() functions.

  • calc() 计算表达式的结果作为属性值, 可使用操作符: + - * /

    #div1 {
      position: absolute;
      left: 50px;
      width: calc(100% - 100px);
      border: 1px solid black;
      background-color: yellow;
      padding: 5px;
    }
    
  • max() { width: max(50%, 300px); }

  • min() { width: min(50%, 300px); }

CSS Gradients(渐变)

@@ Tags: 线性渐变;径向渐变;圆锥渐变
@@ Refer: https://www.w3schools.com/css/css3_gradients.asp

  • CSS Linear Gradients(线性渐变)
    • Syntax:
      • background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
      • background-image: linear-gradient(angle, color-stop1, color-stop2);
      • color-stop 颜色值与一个可选的位置(百分比或长度值表示gradient轴上的位置)
    • Example:
      • background-image: linear-gradient(red, yellow);
      • background-image: linear-gradient(to right, red , yellow);
      • background-image: linear-gradient(to bottom right, red , blue);
      • background-image: linear-gradient(180deg, red, yellow);
  • CSS Radial Gradients
    • Syntax:
      • background-image: radial-gradient(shape size at position, start-color, ..., last-color);
      • shape Defines the shape of the gradient
        • ellipse (default)
        • circle
      • size Defines the size of the gradient
        • farthest-corner (default), 从圆形到最远角
        • farthest-side, 从圆心到最远端
        • closest-corner, 从圆心到最近角
        • closest-side, 从圆心到最近端
      • position Defines the position of the gradient. Default is "center"
      • start-color 类似于color-stop
    • Example:
      • background-image: radial-gradient(red, yellow, green);
      • background-image: radial-gradient(red 5%, yellow 15%, green 60%);
      • background-image: radial-gradient(circle, red, yellow, green);
      • background-image: radial-gradient(farthest-side at 60% 55%, blue, green, yellow, black);
  • CSS Conic Gradients
    • Syntax:
      • background-image: conic-gradient([from angle] [at position,] color [degree], color [degree], ...);
      • By default, angle is 0deg and position is center.
      • If no degree is specified, the colors will be spread equally around the center point.
    • Example:
      • background-image: conic-gradient(red, yellow, green);
      • background-image: conic-gradient(red, yellow, green, blue, black);
      • background-image: conic-gradient(red 45deg, yellow 90deg, green 210deg);

CSS Text Effects

  • text-overflow
    • 表示因为溢出而不能显示的内容如何表示以提示用户.
    • 生效前置条件: white-space: nowrap; overflow: hidden;
    • 可能的值
      • clip Default value. The text is clipped and not accessible
      • ellipsis Render an ellipsis ("...") to represent the clipped text
      • string Render the given string to represent the clipped text
  • word-wrap
    • 允许长词能够被打断并换行到下一行.
    • 可能的值
      • normal
      • break-word
  • word-break
    • 指定当文字到达一行的末尾时,它应该如何断裂(换行)。
    • 可能的值
      • normal Default value. Uses default line break rules
      • keep-all Word breaks should not be used for Chinese/Japanese/Korean (CJK) text
        • 在字(单词)的边界换行, 但不能用于中日韩文字.
      • break-all To prevent overflow, word may be broken at any character(任意字符处)
      • break-word To prevent overflow, word may be broken at arbitrary points(尽量在字的边界, 但会断字)
      • Non-CJK text behavior is the same as value "normal"
  • writing-mode
    • 指定文本行是水平布局还是垂直布局
    • 可能的值
      • horizontal-tb Let the content flow horizontally from left to right, vertically from top to bottom(换行时从上到下)
      • vertical-rl Let the content flow vertically from top to bottom, horizontally from right to left(换行时从右到左)
      • vertical-lr Let the content flow vertically from top to bottom, horizontally from left to right

CSS Web Fonts

@@ Tags: 字体格式;Web网络字体;TTF;OTF;WOFF;EOT;SVG Fonts
@@ Refer: https://www.w3schools.com/css/css3_fonts.asp

Web fonts allow Web designers(设计师) to use fonts that are not installed on the user's computer.

When you have found/bought the font you wish to use, just include the font file on your web server, and it will be automatically downloaded to the user when needed.

Your "own" fonts are defined within the CSS @font-face rule.

In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file.

Tip: Always use lowercase letters for the font URL. Uppercase letters can give unexpected results in IE.

<style> 
@font-face {
   font-family: myFirstFont;
   src: url(sansation_light.woff);
}

@font-face {
   font-family: myFirstFont;
   src: url(sansation_bold.woff);
   font-weight: bold;
}

* {
   font-family: myFirstFont;
}
</style>

<div>
With CSS, websites can use <b>fonts other than the pre-selected "web-safe" fonts</b>.
</div>

Different Font Formats

@@ Refer: https://www.w3schools.com/css/css3_fonts.asp

  • TrueType Fonts (TTF, 轮廓字体:曲线描边字)
    TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most common font format for both the Mac OS and Microsoft Windows operating systems.
  • OpenType Fonts (OTF)
    • OpenType is a format for scalable computer fonts. It was built on TrueType, and is a registered trademark of Microsoft. OpenType fonts are used commonly today on the major computer platforms.
    • 由Microsoft和Adobe公司开发, 是TrueType的超集, 跨平台支持更好.
  • The Web Open Font Format (WOFF)
    WOFF is a font format for use in web pages. It was developed in 2009, and is now a W3C Recommendation. WOFF is essentially(本质上) OpenType or TrueType with compression and additional metadata(本质上是经过压缩并添加元数据的TTF或OTF). The goal is to support font distribution from a server to a client over a network with bandwidth constraints.
  • The Web Open Font Format (WOFF 2.0)
    TrueType/OpenType font that provides better compression than WOFF 1.0.
  • SVG Fonts/Shapes
    SVG fonts allow SVG to be used as glyphs(字形) when displaying text. The SVG 1.1 specification define a font module that allows the creation of fonts within an SVG document(允许在SVG文档中创建字体). You can also apply CSS to SVG documents, and the @font-face rule can be applied to text in SVG documents.
  • Embedded OpenType Fonts (EOT)
    • EOT fonts are a compact(精简) form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages.

CSS Transforms

@@ Tags: Transforms;2D;3D
@@ Refer: https://www.w3schools.com/css/css3_2dtransforms.asp

CSS transforms allow you to move, rotate, scale, and skew elements.

CSS 2D Transforms Methods

With the CSS transform property you can use the following 2D transformation methods:

  • translate() 从当前位置沿着X、Y轴平移
    • transform: translate(50px, 100px);
  • rotate() 顺时针、(负值)逆时针旋转指定角度
    • transform: rotate(20deg);
    • transform: rotate(-20deg);
  • scaleX() 缩放元素的宽度
    • 单位是倍数: 1, 2, 0.5 分别表示: 放大1倍, 2倍, 缩小0.5倍
    • 注意: 元素内容会随之缩放, 列如: 内容会显得模糊
    • transform: scaleX(2);
    • transform: scaleX(0.5);
  • scaleY()
    • transform: scaleY(3);
    • transform: scaleY(0.5);
  • scale()
    • transform: scale(2, 2);
  • skewX()
  • skewY()
  • skew() 将元素沿X轴和Y轴倾斜到给定的角度
    • 理解: 沿X轴倾斜表现为将元素的top与bottom朝X轴的两个方向拉成菱形, 度数表现为拉扯程度, 正负值表明拉扯方向. 沿Y轴倾斜即表现为left与right朝Y轴的两个方向拉扯
    • transform: skew(30deg,30deg);
    • transform: skew(-30deg,30deg);
  • matrix() 2D 操作多合一
    • matrix(scaleX(), skewY(), skewX(), scaleY(), translateX(), translateY())
    • transform: matrix(1, -0.3, 0, 1, 0, 0);

CSS 3D Transforms Methods

分别沿着3D坐标系的X、Y、Z轴旋转指定的度数,符号表示旋转方向

  • rotateX()
  • rotateY()
  • rotateZ()

CSS Transitions(变换)

@@ Tags: 变换;速度曲线
@@ Refer: https://www.w3schools.com/css/css3_transitions.asp

CSS transitions allows you to change property values smoothly, over a given duration(指定时长改变平滑的属性值).

To create a transition effect, you must specify two things:

  • the CSS property you want to add an effect to
  • the duration of the effect

Note: If the duration part is not specified, the transition will have no effect, because the default value is 0.
The transition effect will start when the specified CSS property (width) changes value.

div {
  width: 100px;
  height: 100px;
  background: red;
  transition: width 2s;
}

div:hover {
  width: 300px;
  height: 300px;
}

/* 或多个值 */
/* transition: width 2s, height 4s; */
  • transition
    • transition: width 2s, height 4s;
    • transition: width 2s, height 2s, transform 2s;
  • transition-duration
    Specifies how many seconds or milliseconds a transition effect takes to complete
  • transition-property
    Specifies the name of the CSS property the transition effect is for
  • transition-delay
    This property specifies a delay (in seconds) for the transition effect.
  • transition-timing-function
    • specifies the speed curve of the transition effect(指定变换效果的速度曲线, 即: 在变换过程中, 随着时间的增长与指定值过渡地快慢的关系算法)
    • 可能的值:
      • ease(缓和) - specifies a transition effect with a slow start, then fast, then end slowly (this is default)
      • linear(线性) - specifies a transition effect with the same speed from start to end
      • ease-in(缓入) - specifies a transition effect with a slow start
      • ease-out(缓出) - specifies a transition effect with a slow end
      • ease-in-out(缓入缓出) - specifies a transition effect with a slow start and end
      • cubic-bezier(n,n,n,n)(三次贝塞尔曲线) - lets you define your own values in a cubic-bezier function

CSS Animations

@@ Tags: CSS 动画
@@ Refer: https://www.w3schools.com/css/css3_animations.asp

CSS allows animation of HTML elements without using JavaScript or Flash!

An animation lets an element gradually(逐渐地) change from one style to another.

You can change as many CSS properties you want, as many times as you want(多次改变许多属性).

To use CSS animation, you must first specify some keyframes(关键帧) for the animation.

Keyframes hold what styles the element will have at certain times(关键帧保存了元素在某个时间的
风格
).

/* The animation code */
@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

/* The element to apply the animation to */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

/* 或者百分比 */
@keyframes example {
  0%   {background-color: red;}
  25%  {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}

Note: When an animation is finished, it goes back to its original style.

  • @keyframes
    • The "from" and "to" (which represents 0% (start) and 100% (complete)).
    • It is also possible to use percent. By using percent, you can add as many style changes as you like.
  • animation-name
  • animation-duration
    • Note: This property defines how long an animation should take to complete. If the animation-duration property is not specified, no animation will occur, because the default value is 0s (0 seconds).
  • animation-delay
    • Specifies a delay for the start of an animation.
  • animation-iteration-count
    • Specifies the number of times an animation should run.
    • Uses the value "infinite" to make the animation continue for ever
  • animation-direction
    • Specifies whether an animation should be played forwards(前进), backwards(后退) or in alternate cycles(正反交替).
    • 可能的值
      • normal - The animation is played as normal (forwards). This is default
      • reverse - The animation is played in reverse direction (backwards)
      • alternate - The animation is played forwards first, then backwards
      • alternate-reverse - The animation is played backwards first, then forwards
  • animation-timing-function
    • 指定动画的速度曲线, 同transition-timing-function
  • animation-fill-mode
    • This property specifies a style for the target element when the animation is not playing (before it starts, after it ends, or both).
    • 动画不播放有两种情形:当动画完成后不播放时,或当动画有设置延迟时间未开始播放时
    • 可能的值
      • none - Default value. Animation will not apply any styles to the element before or after it is executing(不影响任何风格)
      • forwards - The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count), 元素将应用动画结束时的风格设置..
      • backwards - The element will get the style values that is set by the first keyframe (depends on animation-direction), and retain this during the animation-delay period, 元素在延时期间将应用第一帧的风格设置.
      • both - The animation will follow the rules for both forwards and backwards, extending the animation properties in both directions, 元素将遵循两者的规则, 在等待期间以及结束后都会应用相应的样式.
  • animation
    A shorthand property for setting all the animation properties.

CSS Filter Property

@@ Refer: https://www.w3schools.com/css/tryit.asp?filename=trycss_ex_images_filters

The CSS filter property adds visual effects (like blur(模糊) and saturation(饱和度)) to an element.

.blur {filter: blur(4px);}
.brightness {filter: brightness(250%);}
.contrast {filter: contrast(180%);}
.grayscale {filter: grayscale(100%);}
.huerotate {filter: hue-rotate(180deg);}
.invert {filter: invert(100%);}
.opacity {filter: opacity(50%);}
.saturate {filter: saturate(7);}
.sepia {filter: sepia(100%);}
.shadow {filter: drop-shadow(8px 8px 10px green);}

CSS box-reflect property

@@ Refer: https://www.w3schools.com/cssref/css_pr_box-reflect.php

The box-reflect property is used to create a reflection of an element.

The value of the box-reflect property can be: below, above, left, or right.

Note: The box-reflect property is non-standard and must be written with -webkit- prefix.

Show demo ❯

img {
  -webkit-box-reflect: below 70px;
}

img {
  -webkit-box-reflect: below 10px linear-gradient(to bottom, rgba(0,0,0,0.0), rgba(0,0,0,0.4));
}

CSS The object-fit and object-position Property

The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container.

This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio(保持纵横比)" or "stretch up and take up as much space as possible(拉伸占据更多空间)".

img {
  width: 200px;
  height: 300px;
  object-fit: contain;
}
  • fill
    This is default. The image is resized to fill the given dimension(尺寸). If necessary, the image will be stretched or squished(压扁) to fit
  • contain
    The image keeps its aspect ratio, but is resized to fit within the given dimension
  • cover
    The image keeps its aspect ratio and fills the given dimension. The image will be clipped(裁剪) to fit.
  • none
    The image is not resized
  • scale-down
    The image is scaled down(缩小) to the smallest version of none or contain.

The CSS object-position property is used to specify how an <img> or <video> should be positioned within its container(指定图片或视频的哪个位置放到容器中).

img {
  width: 200px;
  height: 300px;
  object-fit: cover;
  object-position: 80% 100%;
}

The property values position specifies the position of the image or video inside its content box. First value controls the x-axis and the second value controls the y-axis. Can be a string (left, center or right), or a number (in px or %). Negative values are allowed.

CSS Masking

@@ Tags: 蒙版;掩码;遮罩
@@ Refer: https://www.w3schools.com/css/css3_masking.asp

The CSS mask-image property specifies a mask layer(遮罩层) image.

可以创建一个遮罩层放在一个元素上, 以达到部分或全部隐藏下层元素的部分内容.

The mask layer image can be a PNG image, an SVG image, a CSS gradient, or an SVG <mask> element.

.mask1 {
  -webkit-mask-image: url(w3logo.png);
  mask-image: url(w3logo.png);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}

The mask-repeat property specifies if or how a mask image will be repeated.

Use Gradients as the Mask Layer

.mask1 {
  -webkit-mask-image: linear-gradient(black, transparent);
  mask-image: linear-gradient(black, transparent);
}

CSS Masking Properties

  • mask-image
    Specifies an image to be used as a mask layer for an element
  • mask-mode
    Specifies whether the mask layer image is treated as a luminance mask(亮度遮罩) or as an alpha mask(半透明遮罩)
  • mask-origin
    Specifies the origin position (the mask position area) of a mask layer image
  • mask-position
    Sets the starting position of a mask layer image (relative to the mask position area)
  • mask-repeat
    Specifies how the mask layer image is repeated
  • mask-size
    Specifies the size of a mask layer image

CSS Multiple Columns

@@ Refer: https://www.w3schools.com/css/css3_multiple_columns.asp

The CSS multi-column layout allows easy definition of multiple columns of text - just like in newspapers(将文本分割成多个列).

  • column-count
    Specifies the number of columns an element should be divided into
  • column-gap
    Specifies the gap between the columns(指定列之间的间隙)
  • column-rule-style
    Specifies the style of the rule between columns(列之间分割线的样式).
  • column-rule-width
    Specifies the width of the rule between columns.
  • column-rule-color
    Specifies the color of the rule between columns.
  • column-rule
    This property is a shorthand property for setting all the column-rule-* properties above.
  • column-span
    • Specifies how many columns an element should span across(指定一个元素应该跨越多少列).
    • 可选值: none (默认, 仅跨一列), all 指定元素将跨所有列.
  • column-width
    Specifies a suggested, optimal width for the columns.

CSS Variables

@@ Tags: CSS变量

The var() function is used to insert the value of a CSS variable.

Syntax: var(--name, value)

  • name
    Required. The variable name (must start with two dashes(--) and it is case sensitive!)
  • value
    Optional. The fallback value (used if the variable is not found)

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

First of all(首先): CSS variables can have a global or local scope.

Global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared(全局变量可以在整个文档访问, 局部变量只能在它声明的选择器中访问).

To create a variable with global scope, declare it inside the :root selector. The :root selector matches the document's root element.

To create a variable with local scope, declare it inside the selector that is going to use it(在要使用的选择器中声明它).

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body { background-color: var(--blue); }

h2 { border-bottom: 2px solid var(--blue); }

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

以局部变量重写全局变量

Override Global Variable With Local Variable

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body {
  background-color: var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  --blue: #0000ff; /* local variable will override global */
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

CSS Change Variables With JavaScript

@@ Tags: JavaScript访问CSS变量

<script>
// Get the root element
var r = document.querySelector(':root');

// Create a function for getting a variable value
function myFunction_get() {
  // Get the styles (properties and values) for the root
  var rs = getComputedStyle(r);
  // Alert the value of the --blue variable
  alert("The value of --blue is: " + rs.getPropertyValue('--blue'));
}

// Create a function for setting a variable value
function myFunction_set() {
  // Set the value of variable --blue to another value (in this case "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}
</script>

CSS Using Variables in Media Queries

@@ Tags: CSS媒体查询

Tip: Media Queries are about defining different style rules for different devices (screens, tablets, mobile phones, etc.).

.container {
  --fontsize: 25px;
}

.container {
  padding: 15px;
  font-size: var(--fontsize);
}

@media screen and (min-width: 450px) {
  .container {
    --fontsize: 50px;
  }
}

We create a @media rule that says "When the browser's width is 450px or wider, change the --fontsize variable value of the .container class to 50px."

CSS Box Sizing

@@ Tags: 盒模型

The CSS box-sizing property allows us to include the padding and border in an element's total width and height.

Property Values

  • content-box
    Default. The width and height properties (and min/max properties) includes only the content. Border and padding are not included
  • border-box
    The width and height properties (and min/max properties) includes content, padding and border

By default(content-box), the width and height of an element is calculated like this:

width + padding + border = actual width of an element
height + padding + border = actual height of an element

CSS Media Queries

CSS2 Introduced Media Types

The @media rule, introduced in CSS2, made it possible to define different style rules for different media types.

Unfortunately these media types never got a lot of support by devices, other than the print media type.

CSS3 Introduced Media Queries

Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for a type of device, they look at the capability of the device(CSS3中的媒体查询扩展了CSS2的媒体类型思想: 它们关注的是设备的能力, 而不是设备类型).

Media queries can be used to check many things, such as:

  • width and height of the viewport(视口)
  • width and height of the device
  • orientation (is the tablet/phone in landscape(横屏) or portrait(竖屏) mode?)
  • resolution

Using media queries are a popular technique for delivering a tailored style sheet(提供量身定制的风格) to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).

Media Query Syntax

@@ Refer: https://www.w3schools.com/cssref/css3_pr_mediaquery.php

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false.

@media not|only mediatype and (expressions) {
  CSS-Code;
}

@media not|only mediatype and (mediafeature and|or|not mediafeature) {
  CSS-Code;
}

The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true. When a media query is true, the corresponding style sheet or style rules are applied, following the normal cascading rules(如果指定媒体类型与正在显示该文档的设备类型匹配, 并且所有媒体查询表达式结果为true, 则查询结果为true——声明的CSS样式将被应用).

mediatype(媒体类型)
  • all
    Used for all media type devices
  • print
    Used for printers(用于打印机).
  • screen
    Used for computer screens, tablets, smart-phones etc(用于计算机屏幕、笔记本、平板、智能手机等).
  • speech
    Used for screenreaders that "reads" the page out loud(用于大声“读出”页面的屏幕阅读器).

Media Queries Simple Examples

/* If the viewport width is at least 480, the background color will be lightgreen */
@media screen and (min-width: 480px) {
  body {
    background-color: lightgreen;
  }
}

@media screen and (min-width: 480px) {
  #leftsidebar {width: 200px; float: left;}
  #main {margin-left: 216px;}
}

/* Orientation: Portrait(竖屏) / Landscape(横屏) */
@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

Typical Device Breakpoints

@@ Refer: https://www.w3schools.com/css/css_rwd_mediaqueries.asp

There are tons of screens and devices with different heights and widths, so it is hard to create an exact breakpoint for each device. To keep things simple you could target five groups:

/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {...}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {...}

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {...}

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}

术语 & 概念

替换元素 (Replaced elements)

@@ Tags: 替换元素;object-fit;object-position
@@ Refer: https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element

替换元素指那些独立于CSS格式化模型, 超脱CSS作用域的元素,简单说就是:元素的内容不受CSS影响, 但元素的位置可以通过CSS控制.

典型的替换元素是: <iframe> <video> <embed> <img>

控制元素中的对象在盒模型中的位置

  • object-fit
    • 指定替换元素的内容对象应该如何适配元素盒子
    • 可能得值:
      • none 保持原有尺寸
      • fill 缩放但不保持纵横比去适配盒子
      • cover 裁剪并保持纵横比去适配盒子.
      • contain 缩放并保持纵横比去适配盒子, 如果纵横比不匹配则将会出现黑边.
      • scale-down 内容的尺寸与 none 或 contain 中的一个相同,取决于它们两个之间谁得到的对象尺寸会更小一些。
  • object-position
    • 指定替换元素的内容对象在元素盒子中的对齐方式
    • 语法:
      • object-position: right top;
      • object-position: center;
      • object-position: bottom;
      • object-position: 50% 50%;
      • object-position: 100px -50px;
    • 关于位置描述方面的疑问:
      • 通常来说位置描述有两个参考点, 如 object-position: 100px 25px; 表示 内容对象左上角(参考点b) 位于 元素盒子左上角(参考点a) 右下方(100, 25)像素处
      • object-position: 20% 70%; 根据测试的结果, 两个参考点位于双方坐标的20%,70%处.
      • 即测试结论如下:
        • 使用绝对值时: 双方参考点分别为: 元素盒子的左上角内容对象的左上角
        • 使用百分比时: 双方参考点分别为: 元素盒子的百分比处内容对象的百分比处
      • 测试结果符合结论, 但找不到文档型的资料支撑(已找到, 资料见下).
      • 参考资料:

杂记

html{box-sizing:border-box}*,*:before,*:after{box-sizing:inherit}

/* 上面的代码应该这么阅读 */
html {box-sizing:border-box}

*,
*:before,
*:after{box-sizing:inherit}