CSS Basics

#Introduction to CSS

#How CSS works
>

####What is CSS?
CSS is a language for specifying how documents are presented to users — how they are styled, laid out, etc.

####How does CSS affect HTML?
A CSS rule is formed from:

  • A set of properties, which have values set to update how the HTML content is displayed, for example I want my element's width to be 50% of its parent element, and its background to be red.
  • A selector, which selects the element(s) you want to apply the updated property values to. For example, I want to apply my CSS rule to all the paragraphs in my HTML document.

####A quick CSS example
a stylesheet is applied to the HTML using a element

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My CSS experiment</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
</body>
</html>

CSS:

1
2
3
4
5
6
7
8
9
h1 {
color: blue;
background-color: yellow;
border: 1px solid black;
}
p {
color: red;
}

####How does CSS actually work?

2 steps:

  1. The browser converts HTML and CSS into the DOM (Document Object Model). The DOM represents the document in the computer's memory. It combines the document's content with its style.
  2. The browser displays the contents of the DOM.

Parse progress

####How to apply your CSS to your HTML
3 common ways to apply CSS to HTML

  • External stylesheet(recommanded):
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My CSS experiment</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
</body>
</html>
1
2
3
4
5
6
7
8
9
h1 {
color: blue;
background-color: yellow;
border: 1px solid black;
}
p {
color: red;
}
  • Internal stylesheet

全局有效?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My CSS experiment</title>
<style>
h1 {
color: blue;
background-color: yellow;
border: 1px solid black;
}
p {
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
</body>
</html>
  • Inline styles(It is really bad for maintenance)
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My CSS experiment</title>
</head>
<body>
<h1 style="color: blue;background-color: yellow;border: 1px solid black;">Hello World!</h1>
<p style="color:red;">This is my first CSS example</p>
</body>
</html>

后面两种方法会覆盖第一种方法的设置,第三种会覆盖第二种方法的设置。

#CSS syntax

####A touch of vocabulary
At its most basic level, CSS is consists of two building blocks:

  • Properties: Human-readable identifiers that indicate which stylistic features (e.g. font, width, background color) you want to change.
  • Values: Each specified property is given a value, which indicates how you want to change those stylistic features (e.g. what you want to change the font, width or background color to.)

#####CSS Declarations
Both properties and values are case-sensitive in CSS

There are more than 300 different properties in CSS and nearly an infinite number of different values. Not all pairs of properties and values are allowed; each property has a specific list of valid values defined for it.

Important: If a property is unknown or if a value is not valid for a given property, the declaration is deemed invalid and is wholly ignored by the browser's CSS engine.

Important: In CSS (and other web standards), US spelling has been agreed on as the standard to stick to where uncertainly arises. For example, color (as seen in the above code) should always be spelt color. colour won't work.

#####CSS Declaration blocks

Note: Blocks can sometimes can be nested; in such cases opening and closing braces must be nested logically, in the same fashion as the tags of nested HTML elements. The most common example you'll come across are @-rules, which are blocks beginning with an @ identifier like @media, @font-face, etc (See CSS Statements below).

Note: A declaration block may be empty — this is perfectly valid.

#####CSS Rules
Selectors can get very complicated — you can make a rule match multiple elements by including multiple selectors separated by commas (a group,) and selectors can be chained together, for example I want to select any element with a class of "blah", but only if it is inside an article element, and only while it is being hovered by the mouse pointer.

#####CSS statements
CSS Rules are the main building blocks of a style sheet — the most common block you'll see in CSS. But there are other types of block that you'll come across occasionally — CSS rules are one type of so-called CSS statements. The other types are as follows:

  • At-rules are used in CSS to convery metadata, conditional information, or other descriptive information. They start with an at sign (@), followed by an identifier to say what kind of rule it is, then a syntax block of some kind, ending with a semi-colon (;). Each type of at-rule, defined by the identifier, will have its own internal syntax and semantics. Examples include:

    • @charset and @import (metadata)
    • @media or @document (conditional information, also called nested statements, see below.)
    • @font-face (descriptive information)
    1
    @import 'custom.css';
  • Nested statements are a specific subset of at-rule, the syntax of which is a nested block of CSS rules that will only be applied to the document if a specific condition is matched:

    • The @media at-rule content is applied only if the device which runs the browser matches the expressed condition;
    • the @supports at-rule content is applied only if the browser actually support the tested feature;
    • the @document at-rule content is applied only if the current page matches some conditions.
    1
    2
    3
    4
    5
    6
    @media (min-width: 801px) {
    body {
    margin: 0 auto;
    width: 800px;
    }
    }

Important: Any statement which isn't a ruleset, an at-rule, or a nested statement is invalid and therefore ignored.

####Beyond syntax: make CSS readable

#####Shorthand
Some properties like font, background, padding, border, and margin are called shorthand properties — this is because they allow you to set several property values in a single line, saving time and making your code neater in the process.

This can be used as :

1
2
3
4
5
/* in shorthand like padding and margin, the values are applied
in the order top, right, bottom, left. There are also other
shorthand types, for example two values, which set for example
the padding for top/bottom, then left/right */
padding: 10px 15px 15px 5px

Does this same thing as all these:

1
2
3
4
padding-top: 10px;
padding-right: 15px;
padding-bottom: 15px;
padding-left: 5px;

#Selectors
In CSS, selectors are used to target the HTML elements on our web pages that we want to style. There are a wide variety of CSS selectors available, allowing for fine grained precision when selecting elelents to style.

Selectors can be divided into the following categories:

  • Simple selectors: Match one or more elements based on element type, class, or id.
  • Attribute selectors: Match one or more elements based on their attributes/attribute values.
  • Pseudo-classes: Match one or more elements that exist in a certain state, such as an element that is being hovered over by the mouse pointer, or a checkbox that is currently disabled or checked, or an element that is the first child of its parent in the DOM tree.
  • Pseudo-elements: Match one or more parts of content that are in a certain position in relation to an element, for example the first word of each paragraph, or generated content appearing just before an element.
  • Combinators: These are not exactly selectors themselves, but ways of combining two or more selectors in useful ways for very specific selections. So for example, you could select only paragraphs that are direct descendants of divs, or paragraphs that come directly after headings.

###Simple selectors

####Type selectors aka element selectors
This selector is just a case-insensitive match between the selector name and a given HTML element name.

####Class selectors
The class selector consists of a dot, ., followed by a class name. A class name is any value without spaces put within an HTML class attribute. It is up to you to choose a name for the class. It is also worth knowing that multiple elements in a document can have the same class value and a single element can have multiple class names separated by white space.

HTML:

1
2
3
4
5
<ul>
<li class="first done">Create an HTML document</li>
<li class="second done">Create a CSS style sheet</li>
<li class="third">Link them all together</li>
</ul>

CSS:

1
2
3
4
5
6
7
8
9
/* The element with the class "first" is bolded */
.first {
font-weight: bold;
}
/* All the elements with the class "done" are strike through */
.done {
text-decoration: line-through;
}

####ID selectors
The ID selector consists of a hash/pound symbol (#), followed by the ID name of a given element. Any element can have a unique ID name set with the id attribute. It is up to you what name you choose for the ID. It's the most efficient way to select a single element.

Important: An ID name must be unique in the document. Behaviors regarding duplicated IDs are unpredictable, for example in some browsers only the first instance is counted, and the rest are ignored.

HTML:

1
2
<p id="polite"> — "Good morning."</p>
<p id="rude"> — "Go away!"</p>

CSS:

1
2
3
4
5
6
7
8
#polite {
font-family: cursive;
}
#rude {
font-family: monospace;
text-transform: uppercase;
}

####Universal selector
The universal selector (*) is the ultimate joker. It allows selecting all elements in a page. As it is rarely useful to apply a style to every element on a page, it is often used in combination with other selectors (see Combinators below.)

Important: Careful when using the universal selector. As it applies to all elements, using it in large web pages can have a perceptible impact on performance: web pages can be displayed slower than expected. There are not many instances where you'd want to use this selector.

CSS(apply to all elements in this page):

1
2
3
4
5
* {
padding: 5px;
border: 1px solid black;
background: rgba(255,0,0,0.25)
}

###Attribute selectors

Attribute selectors are a special kind of selector that will match elements based on their attributes and attribute values. Their generic syntax consists of square brackets ([]) containing an attribute name followed by an optional condition to match against the value of the attribute. Attribute selectors can be divided into two categories depending on the way they match attribute values: Presence and value attribute selectors and Substring value attribute selectors.

####Presence and value attribute selectors
These attribute selectors try to match an exact attribute value:

  • [attr] : This selector will select all elements with the attribute attr, whatever its value.
  • [attr=val] : This selector will select all elements with the attribute attr, but only if its value is val.
  • [attr~=val]: This selector will select all elements with the attribute attr, but only if the value val is one of a space-separated list of values contained in attr's value, for example a single class in a space-separated list of classes.

HTML:

1
2
3
4
5
6
7
8
9
10
11
Ingredients for my recipe: <i lang="fr-FR">Poulet basquaise</i>
<ul>
<li data-quantity="1kg" data-vegetable>Tomatoes</li>
<li data-quantity="3" data-vegetable>Onions</li>
<li data-quantity="3" data-vegetable>Garlic</li>
<li data-quantity="700g" data-vegetable="not spicy like chili">Red pepper</li>
<li data-quantity="2kg" data-meat>Chicken</li>
<li data-quantity="optional 150g" data-meat>Bacon bits</li>
<li data-quantity="optional 10ml" data-vegetable="liquid">Olive oil</li>
<li data-quantity="25cl" data-vegetable="liquid">White wine</li>
</ul>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* All elements with the attribute "data-vegetable"
are given green text */
[data-vegetable] {
color: green
}
/* All elements with the attribute "data-vegetable"
with the exact value "liquid" are given a golden
background color */
[data-vegetable="liquid"] {
background-color: goldenrod;
}
/* All elements with the attribute "data-vegetable",
containing the value "spicy", even among others,
are given a red background color */
[data-vegetable~="spicy"] {
color: red;
}

####Substring value attribute selectors

Attribute selectors in this class are also known as "RegExp-like selectors", because they offer flexible matching in a similar fashion to regular expression (but to be clear, these selectors are not true regular expression):

  • [attr|=val] : This selector will select all elements with the attribute attr for which the value is exactly val or starts with val- (careful, the dash here isn't a mistake, this is to handle language codes.)
  • [attr^=val] : This selector will select all elements with the attribute attr for which the value starts with val.
  • [attr$=val] : This selector will select all elements with the attribute attr for which the value ends with val.
  • [attr*=val] : This selector will select all elements with the attribute attr for which the value contains the string val (unlike [attr~=val], this selector doesn't treat spaces as value separators but as part of the attribute value.)

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Classic usage for language selection */
[lang|=fr] {
font-weight: bold;
}
/* All elements with the attribute "data-vegetable" containing the value "not spicy" are turned back to green */
[data-vegetable*="not spicy"] {
color: green;
}
/* All elements with the attribute "data-quantity", for which the value ends with "kg" */
[data-quantity$="kg"] {
font-weight: bold;
}
/* All elements with the attribute "data-quantity", for which the value starts with "optional" */
[data-quantity^="optional"] {
opacity: 0.5;
}

###Pseudo-classes

A CSS pseudo-class is a keyword preceded by a colon (:) that is added on to the end of selectors to specify that you want to style the selected elements only when they are in certain state. For example you might to style an element only when it is being hovered over by the mouse pointer, or a checkbox when it is disabled or checked, or an element that is the first child of its parent in the DOM tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
:active
:any
:checked
:default
:dir()
:disabled
:empty
:enabled
:first
:first-child
:first-of-type
:fullscreen
:focus
:hover
:indeterminate
:in-range
:invalid
:lang()
:last-child
:last-of-type
:left
:link
:not()
:nth-child()
:nth-last-child()
:nth-last-of-type()
:nth-of-type()
:only-child
:only-of-type
:optional
:out-of-range
:read-only
:read-write
:required
:right
:root
:scope
:target
:valid
:visited

####A pseudo-class example
HTML:

1
<a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* These styles will style our link
in all states */
a {
color: blue;
font-weight: bold;
}
/* We want visited links to be the same color
as non visited links */
a:visited {
color: blue;
}
/* We highlight the link when it is
hovered (mouse), activated
or focused (keyboard) */
a:hover,
a:active,
a:focus {
color: darkred;
text-decoration: none;
}

###Pseudo-elements
Pseudo-elements are very much like pseudo-classes, but they have differences. They are keywords — this time preceded by two colons (::) — that can be added to the end of selectors to select a certain part of an element.

1
2
3
4
5
6
::after
::before
::first-letter
::first-line
::selection
::backdrop

####A pseudo-element example:

HTML:

1
2
3
4
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/CSS">CSS</a> defined in the MDN glossary.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/HTML">HTML</a> defined in the MDN glossary.</li>
</ul>

CSS:

1
2
3
4
5
6
/* All elements with an attribute "href", which values
start with "http", will be added an arrow after its
content (to indicate it's an external link) */
[href^=http] ::after {
content: '⤴';
}

###Combinators
Using one selector at a time is useful, but can be inefficient in some situations. CSS selectors become evem more useful when you start combining them to perform fine-grained selections. CSS has several ways to select elements based on how they are related to one another. Those relationships are expressed with combinators as follows (A and B represent any selector seen above):

Combinators Select
AB Any element matching both A and B at the same time.
A B Any element matching B that is a descendant of an element matching A (that is: a child, or a child of a child, etc.)
A > B Any element matching B that is a direct child of an element matching A.
A + B Any element matching B that is the next sibling of an element matching A (that is: the next child of the same parent.)
A ~ B Any element matching B that is among the next sibling of an element matching A (that is: one of the next children of the same parent.)

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<table lang="en-US" class="with-currency">
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Qty.</th>
<th scope="col">Price</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="2" scope="row">Total:</th>
<td>148.55</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Lawnchair</td>
<td>1</td>
<td>137.00</td>
</tr>
<tr>
<td>Marshmallow rice bar</td>
<td>2</td>
<td>1.10</td>
</tr>
<tr>
<td>Book</td>
<td>1</td>
<td>10.45</td>
</tr>
</tbody>
</table>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* Basic table setup */
table {
font: 1em sans-serif;
border-collapse: collapse;
border-spacing: 0;
}
/* All <td>s within a <table and all <th>s within a <table>
Comma is not a combinator, it just allows you to target
several selectors with the same CSS ruleset */
table td, table th {
border : 1px solid black;
padding: 0.5em 0.5em 0.4em;
}
/* All <th>s within <thead>s that are within <table>s */
table thead th {
color: white;
background: black;
}
/* All <td>s preceded by another <td>,
within a <tbody>, within a <table> */
table tbody td + td {
text-align: center;
}
/* All <td>s that are a last child,
within a <tbody>, within a <table> */
table tbody td:last-child {
text-align: right
}
/* All <th>s, within a <tfoot>s, within a <table> */
table tfoot th {
text-align: right;
border-top-width: 5px;
border-left: none;
border-bottom: none;
}
/* All <td>s preceded by a <th>, within a <table> */
table th + td {
text-align: right;
border-top-width: 5px;
color: white;
background: black;
}
/* All pseudo-elements "before" <td>s that are a last child,
appearing within elements with a class of "with-currency" that
also have an attribute "lang" with the value "en-US" */
.with-currency[lang="en-US"] td:last-child::before {
content: '$';
}
/* All pseudo-elements "after" <td>s that are a last child,
appearing within elements with the class "with-currency" that
also have an attribute "lang" with the value "fr" */
.with-currency[lang="fr"] td:last-child::after {
content: ' €';
}

####Multiple selectors on one rule
You can write multiple selectors separated by commas, to apply the same to rule to multiple sets of selected elements at once.

#CSS values and units
5 common used values:

  • Numeric values: Length values for specifying e.g. element width, border thickness, or font size, and unitless integers for specifying e.g. relative line width or number of times to run an animation.
  • Percentages: Can also be used to specify size or length — relative to a parent container's width or height for example, or the default font-size.
  • Colors: For specifying background colors, text colors, etc.
  • Coordinate positions: e.g. for specifying the position of a positioned element relative to the top left of the screen.
  • Functions: For specifying e.g. background images or background image gradients.

###Numeric values

####Length and size

Other absolute units are as follows:

  • mm, cm, in: Millimeters, centimeters, or inches.
  • pt, pc: Points (1/72 of an inch) or picas (12 points.)

There are also relative units, which are relative to the current element's font-size or viewport size:

  • em: 1em is the same as the font-size of the current element (more specifically, the width of a capital letter M.) The default base font-size given to web pages by web browsers before CSS styling is applied is 16 pixels, which means the computed value of 1em is 16 pixels for an element by default. But beware — font sizes are inherited by elements from their parents, so if different font sizes have been set on parent elements, the pixel equivalent of an em can start to become complicated. Don't worry too much about this for now — we'll cover inheritance and font-sizing in more detail in later articles and modules. ems are the most common relative unit you'll use in web development.
  • ex, ch: Respectively these are the height of a lower case x, and the width of the number 0. These are not as commonly used or well-supported as ems.
  • rem: The rem (root em) works in exactly the same way as the em, except that it will always equal the size of the default base font-size; inherited font sizes will have no effect, so this sounds like a much better option than ems, although rems don't work in older versions of Internet Explorer (see more about cross-browser support in Debugging CSS.)
  • vw, vh: Respectively these are 1/100th of the width of the viewport, and 1/100th of the height of the viewport. Again, these are not as widely supported as ems.

#####Unitless line height

1
2
3
4
/*1.5倍行距,也可以加上单位,指定具体的数值*/
p {
line-height: 1.5;
}

#####Number of animations
HTML:

1
<p>Hello</p>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
p {
color: red;
width: 100px;
font-size: 40px;
transform-origin: center;
}
p:hover {
animation-name: rotate;
animation-duration: 0.6s;
animation-timing-function: linear;
animation-iteration-count: 5;
}

###Percentages
You can also use percentage values to specify most things that can be specified by specific numeric values. This allows us to create for example boxes whose width will always shift to be a certain percentage of their parent container's width. This can be compared to boxes that have their width set to a certain unit value (like px or ems), which will always stay the same length, even if their parent container's width changes.

We've also set the font-size to a percentage value: 200%. This works a bit differently to how you might expect, but it does make sense — again, this new sizing is relative to the parent's font-size, as it was with ems.

###Colors

####Keywords
There are around 165 different keywords available for use in modern web browsers

####Hexadecimal values
The next ubiquitous color system is hexadecimal colors, or hex codes. Each hex value consists of a hash/pound symbol (#) followed by six hexadecimal numbers, each of which can take a value between 0 and f (which represents 16) — so 0123456789abcdef. Each pair of values represents one of the channels — red, green and blue — and allows us to specify any of the 256 available values for each (16 x 16 = 256.)

####RGB
The third scheme we'll talk about here is RGB. An RGB value is a function — rgb() — which is given three parameters that represent the red, green and blue channel values of the colors, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255.

HTML:

1
2
3
<p>This paragraph has a red background</p>
<p>This paragraph has a blue background</p>
<p>This paragraph has a kind of pinky lilac background</p>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* equivalent to the red keyword */
p:nth-child(1) {
background-color: rgb(255,0,0);
}
/* equivalent to the blue keyword */
p:nth-child(2) {
background-color: rgb(0,0,255);
}
/* has no exact keyword equivalent */
p:nth-child(3) {
background-color: rgb(224,176,255);
}

####HSL
Slightly less well supported than RGB is the HSL model (not on old versions of IE), which was implemented after much interest from designers — instead of red, green and blue values, the hsl() function accepts hue, saturation, and lightness values, which are used to distinguish between the 16.7 million colors, but in a different way:

  • hue: the base shade of the color. This takes a value between 0 and 360, presenting the angles round a color wheel.
  • saturation: how saturated is the color? This takes a value from 0-100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation
  • lightness: how light, or bright is the color? This takes a value from 0-100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white)

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* equivalent to the red keyword */
p:nth-child(1) {
background-color: hsl(0,100%,50%);
}
/* equivalent to the blue keyword */
p:nth-child(2) {
background-color: hsl(240,100%,50%);
}
/* has no exact keyword equivalent */
p:nth-child(3) {
background-color: hsl(276,100%,85%);
}

####RGBA and HSLA
RGB and HSL both have corresponding modes — RGBA and HSLA — that allow you to set not only what color you want to display, but also what transparency you want that color to have. Their corresponding functions take the same parameters, plus a fourth value in the range 0–1 — which sets the transparency, or alpha channel. 0 is completely transparent, and 1 is completely opaque.
HTML:

1
2
<p>This paragraph has a transparent red background</p>
<p>This paragraph has a transparent blue background</p>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
p {
height: 50px;
width: 350px;
}
/* Transparent red */
p:nth-child(1) {
background-color: rgba(255,0,0,0.5);
position: relative;
top: 30px;
left: 50px;
}
/* Transparent blue */
p:nth-child(2) {
background-color: hsla(240,100%,50%,0.5);
}

####Opacity
There is another way to specify transparency via CSS — the opacity property. Instead of setting the transparency of a particular color, this sets the transparency of all selected elements and their children. Again, let's study an example so we can see the difference.

CSS:

1
2
3
4
5
6
7
8
9
10
/* Red with RGBA, only the background will be half transparent */
p:nth-child(1) {
background-color: rgba(255,0,0,0.5);
}
/* Red with opacity, the box will be all half transparent including the text in it*/
p:nth-child(2) {
background-color: rgb(255,0,0);
opacity: 0.5;
}

###Functions
already seen functions in action in the Colors section, with rgb(), hsl(), etc.:

1
2
3
4
5
6
7
8
9
10
11
background-color: rgba(255,0,0,0.5);
background-color: hsla(240,100%,50%,0.5);
/* calculate the new position of an element after it has been rotated by 90 degress */
transform: rotate(45deg);
/* calculate the new position of an element after it has been moved across 50px and down 60px */
transform: translate(50px, 60px);
/* calculate the computed value of 90% of the current width minus 15px */
width: calc(90%-15px);
/* fetch an image from the network to be used as a background image */
background-image: url('myimage.png');

anytime you see a name with brackets after it, containing one or more values separated by commas, you are dealing with a function.

#Cascade and inheritance

In a previous article, we got into the various CSS selectors. At some point in your work, you'll find yourself in the situation where multiple CSS rules will have selectors matching the same element. In such cases, which CSS rule "wins", and ends up being the one that is finally applied to the element? This is controlled by a mechanism called the Cascade; this is also related to inheritance (elements will take some property values from their parents, but not others.) In this article we will define what the cascade is, what selector weight is, and how properties inherit from different rules.

###The cascade(层叠)
these are listed in order of weight — earlier ones will overrule later ones:

  1. Importance
  2. Specificity
  3. Source order

####Importance
In CSS, there is a special piece of syntax you can use to make sure that a certain rule will win over all overs: !important. Adding this to the end of a property value will give it superpowers.

HTML:

1
2
<p class="better">This is a paragraph.</p>
<p class="better" id="winning">One selector to rule them all!</p>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#winning {
background-color: red;
border: 1px solid black;
}
.better {
background-color: gray;
border: none !important;
}
p {
background-color: blue;
color: white;
padding: 5px;
}

Note: The only way to override this !important declaration would be to include another !important declaration of the same specificity, later in the source order.

It is useful to know that !important exists so that you know what it is when you come across it in other people's code. BUT. We would advise you to never use it unless you absolutely have to. One situation in which you may have to use it is when you are working on a CMS where you can't edit the core CSS modules, and you really want to override a style that can't be overridden in any other way. But really, don't use it if you can avoid it. Because !important changes the way the cascade normally works, it can make debugging CSS problems really hard to work out, especially in a large stylesheet.

Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:

  1. Declarations in user agent style sheets (e.g. the browser's default styles, used when no other styling is set.)
  2. Normal declarations in user style sheets (custom styles set by a user to override web developer's styles.)
  3. Normal declarations in author style sheets (these are the styles set by us, the web developers!)
  4. Important declarations in author style sheets
  5. Important declarations in user style sheets

####Specificity

ID > class > element

The amount of specificity a selector has is based on something called the selector weight. This has four different values, which can be thought of as thousands, hundreds, tens and ones — four single digits in four columns. The selector weight is calculated based on the selector types of its sub-parts:

  1. Thousands: One if the matching selector is inside a <style> element or the declaration is inside a style attribute (such declarations don't have selectors, so their specificity is always simply 1000.) Otherwise 0.
  2. Hundreds: One for each ID selector contained inside the overall selector.
  3. Tens: One for each class selector, attribute selector or pseudo-class contained inside the overall selector.
  4. Ones: One for each element selector and pseudo-element contained inside the overall selector.

Note: Universal selector (*), combinators (+, >, ~, ' ') and negation pseudo-class (:not) have no effect on specificity.

example:

Selector Thousands Hundreds Tens Ones Total specificity
h1 0 0 0 1 0001
#important 0 1 0 0 0100
h1 + p::first-letter 0 0 0 3 0003
li > a[href=*"en-US"] > .inline-warning 0 0 2 2 0022
#important div > div > a:hover, inside a <style> element 1 1 1 3 1113

Note: If multiple selectors have the same importance and specificity, which element wins is decided by which comes later in the Source order.

####Source order

###Inheritance
The idea is that some property values applied to an element will be inherited by that element's children, and some won't.

  • For example, it makes sense for font-family and color to be inherited, as that makes it easy for you to set a site-wide base font by applying a font-family to the <html> element; you can then override the fonts on individual elements where needed. It would be really annoying to have to set the base font separately on every element.
  • As another example, it makes sense for margin, padding, border, and background-image to NOT be inherited. Imagine the styling/layout mess that would occur if you set these properties on a container element and had them inherite inherited by every single child element, and then had to unset them all on each individual element!

Which properties are inherited by default and which aren't is largely down to common sense. If you want to be sure however, you can consult the CSS Reference — each separate property page starts off with a summary table including various details about that element, including whether it is inherited or not.

####Controlling inheritance
CSS provides three special values to handle inheritance:

  • inherit : This value sets the property value applied to a selected element to be the same as that of its parent element.
  • initial : This value sets the property value applied to a selected element to be the same as the value set for that element in the browser's default style sheet. If no value is set by the browser's default style sheet and the property is naturally inherited, then the property value is set to inherit instead.
  • unset : This value resets the property to its natural value, which means that if the property is naturally inherited it acts like inherit, otherwise it acts like initial.

HTML:

1
2
3
4
5
6
<ul>
<li>Default <a href="#">link</a> color</li>
<li class="inherit">Inherit the <a href="#">link</a> color</li>
<li class="initial">Reset the <a href="#">link</a> color</li>
<li class="unset">Unset the <a href="#">link</a> color</li>
</ul>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
body {
color: green;
}
.inherit a {
color: inherit;
}
.initial a {
color: initial
}
.unset a {
color: unset;
}

#The box model

###Box properties
BOX MODEL

Note: Margins have a specific behavior called margin collapsing: When two boxes touch against one another, the distance between them is the value of the largest of the two touching margins, and not their sum.

###Active learning: playing with boxes

###Advanced box manipulation

####Overflow
overflow property. It takes several possible values, but the most common are:

  • auto: If there is too much content, the overflowing content is hidden and scroll bars are shown to let the user scroll to see all the content.
  • hidden: If there is too much content, the overflowing content is hidden.
  • visible: If there is too much content, the overflowing content is shown outside of the box (this is usually the default behavior.)

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<p class="autoscroll">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Mauris tempus turpis id ante mollis dignissim. Nam sed
dolor non tortor lacinia lobortis id dapibus nunc. Praesent
iaculis tincidunt augue. Integer efficitur sem eget risus
cursus, ornare venenatis augue hendrerit. Praesent non elit
metus. Morbi vel sodales ligula.
</p>
<p class="clipped">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Mauris tempus turpis id ante mollis dignissim. Nam sed
dolor non tortor lacinia lobortis id dapibus nunc. Praesent
iaculis tincidunt augue. Integer efficitur sem eget risus
cursus, ornare venenatis augue hendrerit. Praesent non elit
metus. Morbi vel sodales ligula.
</p>
<p class="default">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Mauris tempus turpis id ante mollis dignissim. Nam sed
dolor non tortor lacinia lobortis id dapibus nunc. Praesent
iaculis tincidunt augue. Integer efficitur sem eget risus
cursus, ornare venenatis augue hendrerit. Praesent non elit
metus. Morbi vel sodales ligula.
</p>

CSS:

1
2
3
4
5
6
7
8
9
10
p {
width : 400px;
height : 2.5em;
padding: 1em 1em 1em 1em;
border : 1px solid black;
}
.autoscroll { overflow: auto; }
.clipped { overflow: hidden; }
.default { overflow: visible; }

####Background clip
Box backgrounds are made up of colors and images, stacked on top of each other (background-color, background-image.) They are applied to a box and drawn under that box. By default, backgrounds extend to the outer edge of the border. This is often fine, but in some cases it can be annoying (what if you have a tiled background image that you want to only extend to the edge of the content?) This behaviour can be adjusted by setting the background-clip property on the box.

HTML:

1
2
3
<div class="default"></div>
<div class="padding-box"></div>
<div class="content-box"></div>

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
div {
width : 60px;
height : 60px;
border : 20px solid rgba(0, 0, 0, 0.5);
padding: 20px;
margin : 20px 0;
background-size : 140px;
background-position: center;
background-image : url('https://mdn.mozillademos.org/files/11947/ff-logo.png');
background-color : gold;
}
.default { background-clip: border-box; }
.padding-box { background-clip: padding-box; }
.content-box { background-clip: content-box; }

####Outline
Last but not least, the outline of a box is something that looks like a border but which is not part of the box model. It behaves like the border but is drawn on top of the box without changing the size of the box (to be specific, the outline is drawn outside the border box, inside the margin area.)

###Types of CSS boxes

The type of box applied to an element is specified by the display property. There are many different values available for display, but in this article we will focus on the three most common ones: block, inline, and inline-block.

  • A block box is defined as a box that's stacked upon other boxes (i.e. content before and after the box appears on a separate line), and can have width and height set on it. The whole box model as described above applies to block boxes.
  • An inline box is the opposite of a block box: it flows with the document's text (i.e. it will appear on the same line as surrounding text and other inline elements, and its content will break with the flow of the text, like lines of text in a paragraph.) Width and height settings have no effect on inline boxes; any padding, margin and border set on inline boxes will update the position of surrounding text, but will not affect the position of surrounding block boxes.
  • An inline-block box is something in between the first two: It flows with surrounding text without creating line breaks before and after it like an inline box, but it can be sized using width and height and maintains its block integrity like a block box — it won't be broken across paragraph lines (in the below example the inline-box goes onto the 2nd line of text, as there is not enough space for it on the first line, and it won't break across two lines.)

#Debugging CSS