Why write this article?

CSS technology has evolved into a complex technology defined by more than 80 W3C specifications, with nearly four to five hundred attributes. CSS has grown so large that the average person can no longer fit it into his or her head. Therefore, whether as a CSS beginner or skilled, when writing CSS code, there will be a need to query the usage and rules of a property from time to time. But these knowledge points are scattered in all corners of the Internet, we must use search engines to find. Although there are web tools like MDN, it is indexed by English letters, which sometimes does not meet our needs. Thus, this article is not intended to replace MDN or search engines, but to supplement them.

It is also not easy to organize all the commonly used attributes through functional usage, and this article is presented at medium.com/free-cod… As a reference frame, this article was translated and sorted out, and some outdated content was deleted and some new content was added that was not involved in the original text. Most of the code examples are taken directly from MDN because they are pretty good. This article has more than 120 pages and 26,000 words in Word. It is really a huge project, so I have published it here in two parts.

If you need a Word/PDF version of this article, you can scan me at the end of the article.

It is impossible to include all the information on all CSS properties in a single article, so links to recommended reading articles are provided at the end of each chapter.

This is the first half of two parts, and this article contains the following:

Introduction to CSS, Add CSS, selectors, Property selectors, Pseudo-classes, pseudo-elements, Priorities, Inheritance, Box model, box-sizing, Units, Backgrounds, Fonts, Typography, Borders, Margins, margins.

The second half of the article will contain:

Color, Display Type, Position, Float and Clear float, URL, Calc, Comments, Custom Properties, Z-Index, Flex, Grid, Table, Center, List, Media Query and Responsive Design, function Query, filter, Transform, Transition, Animation ), normalize.css, error handling, browser prefixes, printing

So let’s get started.

1. Introduction to the CSS

Cascading Style Sheets (CSS) is used to Style and format your web page – such as changing the font, color, size, and spacing of web content, breaking it up into columns, or adding animations and other decorative effects. It is a language for specifying to users how documents are rendered — how they are styled, laid out, and so on.

The advantage of CSS

  1. Separation of content and presentation
  2. The performance of the web page is uniform and easy to modify
  3. Rich style, make the page layout more flexible
  4. Reduce the amount of code in web pages, increase the speed of web browsers, and save network bandwidth
  5. The use of independent pages of CSS, conducive to web pages by the search engine included

How does CSS affect HTML

Web browsers apply CSS rules to documents to affect how they are displayed. A CSS rule consists of the following:

  • A set of attributes whose values update how the HTML content is displayed. For example, I want the width of the element to be 50% of its parent, or the background of the element to be red.
  • A selector that selects the elements to which you want to apply the latest attribute values. For example, I want to apply my CSS rules to all paragraphs in my HTML document.

2. Add the CSS

There are three different ways to apply CSS to HTML documents:

1. External style sheets

External stylesheets are when you save your CSS in a separate.css file and reference it from the HTML <link> element. The HTML file now looks like this:


      
<html>
  <head>
    <meta charset="utf-8">
    <title>The CSS test page</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>This is an example CSS reference</p>
  </body>
</html>Copy the code

And the following CSS file:

h1 {
  color: blue;
  background-color: yellow;
  border: 1px solid black;
}

p {
  color: red;
}Copy the code

This approach is arguably the best because you can style multiple documents using a single stylesheet and update your CSS in one place.

2. Internal style sheets

An internal style sheet means that instead of using an external CSS file, you place your CSS inside a <style> element, which is contained within the HTML head. The HTML now looks like this:


      
<html>
  <head>
    <meta charset="utf-8">
    <title>The CSS test page</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 an example CSS reference</p>
  </body>
</html>Copy the code

This is useful in some cases, but it’s not as efficient as external stylesheets — in a website, the CSS will need to be repeated on every page and need to be changed in multiple places when updated.

3. Inline style

Inline styles are CSS declarations that affect only one element, and are included by the style attribute:


      
<html>
  <head>
    <meta charset="utf-8">
    <title>The CSS test page</title>
  </head>
  <body>
    <h1 style="color: blue; background-color: yellow; border: 1px solid black;">Hello World!</h1>
    <p style="color:red;">This is an example CSS reference</p>
  </body>
</html>Copy the code

Don’t use this method unless you have to! Because it is difficult to maintain, and it also mixes CSS presentation style information with HTML structure information, making CSS difficult to read and understand. Keeping the different types of code separate makes the developer’s life easier.

Three, selector

CSS selectors specify which elements the CSS rules apply to.

Basic selector

Suppose we have a P element on the page, and we want the text in the P element to be yellow.

We can use the type selector to select all elements of a certain type on the page. Here we can use p to select all p elements. CSS is written as follows:

p {
  color: yellow;
}Copy the code

Each HTML tag can be used as a CSS selector, such as div, SPAN, img, etc.

If a type selector matches multiple elements on a page, those elements are affected by CSS Settings.

In addition to type selectors, there are two very common selectors: the class selector and the ID selector, which are used to select specific elements on a page.

The biggest difference between the two selectors is that the class value can be set on multiple elements, but the ID of each element in a document should be unique.

The syntax for the Class selector is.classname, and the syntax for the ID selector is # idName.

Example Class selector:

<p class="dog-name"> </p>. Dog-name {color: yellow; }Copy the code

ID selector example:

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

#dog-name {
  color: yellow;
}
Copy the code

Universal selector

The universal selector selects all nodes. It is also often used with a noun space to select all elements within that space. Such as:

.name * {
  color: yellow;
}Copy the code

Combinatorial selector

CSS also supports more powerful combinatorial selectors.

Elements are selected by class or ID as an accessory to the type selector.

The following is an example:

Use the class

<p class="dog-name"< p style = "max-width: 100%; clear: both; }Copy the code

Use the ID

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

p#dog-name {
  color: yellow;
}
Copy the code

The class or ID selector can be used to select multiple elements. Why add the element type in front of it? The reason for this is to increase the priority of the selector so that the CSS styles in it override the previous low-level styles. See the priorities section for details.

Multiple class selectors

You can select an element by concatenating the two classes.

<p class="dog-name roger"</p>. Dog-name. Roger {color: yellow; }Copy the code

Class and ID are combined

<p class="dog-name" id="roger"> Name </p>. Dog-name#roger {
  color: yellow;
}
Copy the code

Packet selector

You can apply the same CSS style to different selectors, using commas to separate each selector:

<p>Name:</p>
<span class="dog-name">Zhang SAN</span>

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

It is also possible to make the code clearer by making each selector occupy one line:

p..dog-name {
  color: yellow;
}
Copy the code

Descendant selector

If we have a SPAN tag nested within a P tag, we can use the descendant selector to select the SPAN elements in all P elements, and the span elements not in the P element will not be selected. Descendant selectors use the ‘space operator.

<span>Hello!</span>
<p>Name:<span class="dog-name">Zhang SAN</span>
</p>

p span {
  color: yellow;
}
Copy the code

Descendant selectors can select not only the children of an element, but also its descendants.

Child element selector

If we specify that only child elements can be selected, we use the child element selector, which uses the ‘>’ operator.

p > span {
  color: yellow;
}
Copy the code

Only all span elements directly nested within the P element will change color.

Adjacent sibling selectors

The ‘+’ operator selects adjacent elements, meaning that the second element is adjacent to the first and has a common parent element.

<p>This is a line of text</p>
<span>This line of writing is yellow</span>

p + span {
  color: yellow;
}Copy the code

Universal sibling selector

The ‘~’ operator selects sibling elements, that is, subsequent elements are anywhere after the first, and both elements have the same parent element.

<p>This is a line of text</p>
<span>We are all yellow</span>
<span>We are all yellow</span>
<span>We are all yellow</span>

p ~ span {
  color: yellow;
}Copy the code

In addition to the above selectors, there are several other selectors:

  • Property selector
  • pseudo-classes
  • Pseudo elements

I will separate these three out and introduce them in their own paragraphs.

Property selector

CSS property selectors match elements with existing property names or property values.

Properties have selectors

The first class of selectors is called attribute existence selectors. We use the [] syntax to determine whether an element has an attribute. For example, p[id] selects all p elements on the page that have an ID attribute, regardless of their attribute value.

p[id] {
  / *... * /
}Copy the code

Exact attribute value selector

Inside the brackets, we can specify the value of the property, and only when the property and value match exactly will the corresponding CSS style be applied.

p[id="my-id"] {
  / *... * /
}Copy the code

Attribute value fuzzy match selector

[attr=value] stands for full match, and there are other fuzzy match operators:

  • [attr*=value] : indicates an element with an attribute named attr and whose value contains “value”.
  • [attr^=value] : indicates an element with an attribute named attr whose value starts with “value”.
  • [attr$=value] : represents an element with an attribute named attr whose value ends in “value”.
  • [attr | = value] : said with named after attr attribute, and attribute values for the “value” or “value” as the prefix of the element.
  • [attr~=value] : indicates an attribute named attr. The attribute value is a whitespace separated list. At least one of the attributes matches “value”.

The values of all the property selectors above are case sensitive.

If you add the letter I before the closing parenthesis, the case of the attribute value is ignored. It is supported in many browsers, but not all. Visit CaniUse for compatibility.

Five, the pseudo class

Pseudo-classes are keywords added to the selector that specify the special state of the element to be selected. For example, :hover can be used to change the color of a button when the user hovers over it.

All pseudo-classes begin with a colon ‘:’

Some of the most commonly used pseudo-classes are listed below:

  • :active – Matches elements activated by the user. When interacting with the mouse, it represents the time between the user pressing a key and releasing it.
  • : Checked – Represents any option element in the radio, checkbox, or SELECT element that is in the selected state.
  • :default – Sets the style of the default value of the form control.
  • :disabled – Indicates any disabled elements.
  • :empty – Represents an element that has no children.
  • :enabled – Indicates any enabled element (as opposed to :disabled).
  • :first-child – Represents the first element in a set of sibling elements.
  • :focus – Represents the element that gets focus (such as form input). It is triggered when the user clicks or touches the element or selects it using the keyboard’s TAB key.
  • :hover – Sets the style to hover over an element.
  • :last-child – Represents the last child of the parent element.
  • :link – Selects all links that have not yet been accessed.
  • :not(X) – Matches elements that do not match the description of parameter selector X. For example: p:not(.fancy) selects a p element whose class name is not.fancy.
  • :nth-child() – Selects the element at the specified position.
  • :nth-last-child() – Selects the element in the specified position, but evaluates from the last element.
  • :only-child – Represents the only child element belonging to a parent element.
  • :required – Represents the element with the Required attribute set.
  • :root – Matches the root element of the document tree. For HTML, :root represents the < HTML > element.
  • :target – Represents a unique page element (target element) whose ID matches the current URL fragment.
  • : valid-indicates that the content validates the correct or other
    elements.
  • :visited – Indicates a link that the user has visited.

For example, let’s say we have an A link on the page and set the text to yellow.

a {
  color: yellow;
}Copy the code

However, when we click on the link with the mouse and look at the A element after it is accessed, its text color changes to blue. The reason is that when the mouse clicks, link A changes its state and becomes active. When it is visited, it is in :visited state, unless the user has cleared the browsing history.

Therefore, to make the A link yellow in all states, write:

a.a:visited.a:active {
  color: yellow;
}Copy the code

The :nth-child() pseudo-class will enclose an expression of the form an+b in parentheses. Here are some examples of expressions:

  • Tr: nth-Child (2n+1)/tr: nth-Child (odd) – Denotes odd rows in an HTML table.
  • Tr :nth-child(2n)/tr: nth-Child (even) – Denotes even rows in an HTML table.
  • Span :nth-child(0n+1) – Represents the first span element of the child element, which has the same effect as the :first-child selector.
  • Span :nth-child(1) – Indicates that the tag with the first neutron element of the parent element and the name SPAN is selected.
  • Span :nth-child(-n+3) – matches the span elements of the first three child elements.

:not()

When we want to add a split line to each li element of a navigation menu, we usually do this:

Start by adding a border to the element

/* Add a border */
.nav li {
  border-right: 1px solid # 666;
}Copy the code

Then remove the border for the last element

/* Remove the border */
.nav li:last-child {
  border-right: none;
}Copy the code

This is too cumbersome to set up, use the :not() pseudo-class to achieve the same effect:

.nav li:not(:last-child) {
  border-right: 1px solid # 666;
}Copy the code

False elements

A pseudo-element is a keyword appended to the end of a selector that allows you to style specific parts of the selected element. For example :first-line pseudo-elements change the style of the first line of a paragraph.

Pseudo-elements begin with two colons’ :: ‘.

Only one pseudo-element can be used in a selector. The pseudo-element must follow the simple/base selector in the statement.

Note: According to the specification, double colons (:) should be used instead of single colons (:) to distinguish pseudo-classes from pseudo-elements. However, since older versions of the W3C specification did not make this distinction, most browsers today support both ways of representing pseudo-elements.

Here are some common pseudo-elements:

  • ::after – Creates a pseudo-element as the last child of the selected element.
  • ::before – Creates a pseudo-element that will be the first child of the matched selected element.
  • ::first-letter – Selects the first letter of the first row of a block-level element.
  • ::first-line – Selects the first row of a block-level element.
  • :: Selection – Applies to parts of a document that are highlighted by the user (such as those selected using a mouse or other selection device).

For example, let’s make the first line of each paragraph larger:

p::first-line {
  font-size: 1.6 rem;
}Copy the code

Or make one text in each paragraph bold red:

p::first-letter {
  font-weight: bolder;
  color: red;
}Copy the code

It is also possible to use ::before and ::after pseudo-elements to insert other content before or after the text:

.boring-text::before {
   content: "Boring! - >";
   color: red;
}
.exciting-text::after {
  content: "< -make people happy!"; 
  color: green;
}Copy the code

7. Priority

What happens when there are multiple declarations (different selectors) for the same element, especially how does the same attribute affect the element?

For example, if the page has a p element:

<p class="dog-name"> name < / p >Copy the code

We use the class selector to set the color of the text:

.dog-name {
  color: yellow;
}Copy the code

Then use the type picker to set the text to another color:

p {
  color: red;
}Copy the code

So, what color should the text on the page be? Why is that?

This is where CSS priority comes in. Priority is the weight assigned to a given CSS declaration, determined by the value of each selector type in the matched selector. The higher-value selector overwrites the lower-value selector, and when the values are equal, the following declaration is applied to the elements.

How to calculate the value of priority?

There is a set of rules for calculating priorities.

We divide all CSS selectors into four levels, each starting at 0, and write them like this: 0, 0, 0, 0. Of the four levels, the leftmost is the highest and the rightmost is the lowest. For example, 1, 0, 0, 0 is higher than 0, 1, 0, 0, 0, 1 is the lowest.

Now, let’s introduce each of the four levels.

Level 1

The first level, the number on the far right, is the lowest.

Level 1 selectors are mainly type selectors. When there is one type selector in the selector, the value of the number is increased by one. If there are more than one type selectors, the value of the number is changed to the number of selectors.

Such as:

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 */Copy the code

Level 2

There are three level 2 selectors:

  • The class selector
  • Pseudo class selector
  • Property selector

They correspond to the second number on the right.

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

Level 2 selectors can be mixed with level 1 selectors:

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

Here’s a trick where we can repeat the class selector to increase the selector’s priority:

.name {}              /* 0 0 1 0 */
.name.name {}         /* 0, 0, 2, 0 */
.name.name.name {}    /* 0, 0, 3, 0 */Copy the code

Level 3

Level 3 selectors mainly refer to ID selectors.

#name {}                    /* 0 1 0 0 */
.user #name {}              /* 0 1 1 0 */
#name span {}               /* 0 1 0 1 */Copy the code

Level 4

Level 4 mainly refers to the inline style, which is the highest level.

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

From level 1 to level 4, the preference of the selector increases, and the higher-level selector overrides the styles of the lower-level selector. Of course, there is a level 5 keyword, it is! Important, but we do not recommend using it.

The end of this section gives you an online tool that automatically calculates the priority level of the selector.

Read more about CSS priorities in the MDN article CSS Priorities

Eight, inheritance,

In CSS, child elements can inherit attributes from their parent elements. I’m talking about some properties here, not all of them.

It makes sense for certain attributes to be inherited, which helps us write cleaner CSS because we don’t have to set the attribute repeatedly on every child element.

Supported inherited properties

Some of the more common default inheritable properties are listed below.

  • 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

Here’s an example:

<p>This passage contains<em>Something that can inherit color</em>The text.</p>

p { color: green; }Copy the code

The text in the em element automatically inherits the color of its parent p element:

Mandatory attribute inheritance

What do YOU do to have an attribute that is not inherited by default inherit from its parent element attribute? The keyword inherit should be used.

body {
  background-color: yellow;
}
p {
  background-color: inherit;
}Copy the code

Force attributes not to inherit

The CSS has a revert keyword that restores property values to the original browser default, rather than inheriting from the parent element. However, the browser support for this keyword is not very good, so it is rarely used. So the common approach is to set another value to the attribute to override the value inherited from the parent element.

other

In addition to inherit and Revert, CSS has two keywords:

  • Initial: The initial (or default) value of a property is applied to an element, which is used to restore all CSS properties to their initial state.
  • Unset: Sets the property to the inherited value if the value is inherited from its parent, or resets the property to its original value if the parent style is not inherited. In other words, it will use inherit style first, followed by initial style.

9. Box model

When laying out a document, the browser’s rendering engine represents all elements as rectangular boxes based on the CSS base box model.

The box model explains the size of an element.

Each box is made up of four parts, or areas:

  • The content area
  • padding
  • border
  • margin

It will look more intuitive in pictures:

The light blue area is the content area, with the padding around it, and then the border and margin outside.

By default, setting width or height on an element will apply to the content area. All padding and border values are outside width and height.

Of course, box-sizing allows you to change how elements are evaluated, which we’ll cover in a minute.

Ten, Box – sizing

The box-sizing attribute defines how the browser should calculate the total width and height of an element.

In the default definition of the box model, width and height of an element are applied only to the element’s content area. If the element has any border or padding, the width and height of the box drawn to the screen will be added to the set border and padding values.

This feature is especially annoying when we implement responsive layouts.

The box-sizing attribute, which can be used to adjust these behaviors, has two values:

  • Content-box: default value. If you set the width of an element to 100px, the content area of the element will be 100px wide, and the width of any borders and margins will be added to the width of the final drawn element.
  • Border-box: Set the border and margin values to be contained within width. That is, if you set the width of an element to 100px, then the 100px will contain the border and padding. The actual width of the content area is width minus (border + padding). In most cases, this makes it easier to set the width and height of an element.

Here’s an example:

The total width of the first div is 160px + (2 * 20px) + (2 * 8px) = 216px, and the total height is 80px + (2 * 20px) + (2 * 8px) = 136px;

The second div has a total width of 160px and a total height of 80px.

We often see this setting at the beginning of some CSS code:

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

The size calculation of all elements is changed to the border-box mode, which is easier and more convenient for the page layout.

Xi. Units

Unit is one of the most common things we use in CSS. It is used for many CSS properties, such as width, margin, padding, font-size, border-width, text-shadow, and so on.

The following sections introduce the units of the CSS one by one.

pixel

The most widely used unit. Related to the display device, for a screen display, it is usually a device pixel (dot) display, for printers and high-resolution screens, a CSS pixel means multiple device pixels, so the number of pixels per inch stays around 96.

The percentage

Percentage values are often sized based on the parent object. The percentage value consists of a <number> concrete value followed by the % sign. Just like any CSS unit, there is no space allowed between % and value.

Many length attributes use percentages, such as width, height, margin, and padding. Percentages can also be seen in the font size property, where the text size is directly related to the text size of its parent element.

Here’s an example:

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

Offline unit

Offline units here refer to the various units of measurement we had in the real world before computers.

  • Cm: one centimeter (37.8px on screen)
  • Mm: one millimeter (0.1cm)
  • Q: A quarter of a millimeter
  • In: one inch (96px on screen)
  • Pt: 1 inch = 72pt
  • PC: 1PC = 12pt

Relative unit

  • Em: This unit represents the computed value of the font size of the element. If used with the font size attribute itself, it inherits the font size of the parent element.
  • Rem: Similar to em, this represents the font size of the root element (for example, the font size of the < HTML > element). When used with the font size of the root element, it represents its initial value. We can set the font size only once, and then control the size of the entire page.
  • Ex: Refers to the height of the letter ‘x’, which varies from font to font. For many fonts, 1ex ≈ 0.5em.
  • Ch: Similar to the ex unit, it is the height of the character ‘0’.

A unit of visual area proportion

  • Vw: indicates the percentage of viewport width. 1vw = 1/100 of viewport width.
  • Vh: indicates the percentage of viewport height. 1vh = 1/100 viewport height.
  • Vmin: Determine which is the smallest between the height and width of the viewing area. 1vmin = 1/100 of the minimum value.
  • Vmax: determine which is the largest between the height and width of the viewport. 1vmax = 1/100 of the maximum value.

fr

The FR unit represents a variable length in a grid container. Used in grid-template-columns, grid-template-rows, and related properties.

For more information about units, read CSS: EM, PX, PT, CM, in… And 7 CSS Units you May Not Know

Xii. Background

You can change the background color of an element or the background image style by using the following background related properties.

  • background-color
  • background-image
  • background-clip
  • background-position
  • background-origin
  • background-repeat
  • background-attachment
  • background-size

Background is shorthand for these attributes and is used to define all background attributes at once, including color, image, origin and size, repeat, and so on.

The background-color property is used to change the background color of an element. The value of the property is either the color value or the keyword “transparent”.

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

The background-image attribute is used to set one or more background images for an element, and to introduce images by specifying the image location URL.

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

Background-clip Sets whether the element’s background (background image or color) extends below the border. It has four values:

  • Border-box: The default, the background extends to the outer edge of the border (but below it).
  • Padding-box: The background extends to the outer edge of the padding. It’s not drawn to the border.
  • Content-box: The background is clipped to the edge of the content box.
  • Text: Foreground scenery with the background cropped to text.

Here is an example screenshot on MDN:

Background-position Sets the initial position for each background image. This position is relative to the position layer defined by background-Origin.

/* Keyword value */
background-position: top;
background-position: bottom;
background-position: left;
background-position: right;
background-position: center;

/* Percentage value */
background-position: 25% 75%;

/* Length value */
background-position: 0 0;
background-position: 1cm 2cm;
background-position: 10ch 8em;

/* Multigraph setup */
background-position: 0 0, center;

/* Offset */
background-position: bottom 10px right 20px;
background-position: right 3em bottom 10px;
background-position: bottom 10px right;
background-position: top right 10px;

/* Global value */
background-position: inherit;
background-position: initial;
background-position: unset;Copy the code

Example:

If the background image is smaller than the size of the element, you can specify how the background image is repeated using the background-repeat attribute. The background image can be repeated along the horizontal axis, vertical axis, both axes, or not at all.

/* Single-value syntax */
background-repeat: repeat-x;
background-repeat: repeat-y;
background-repeat: repeat;
background-repeat: space;
background-repeat: round;
background-repeat: no-repeat;

/ * double value syntax: level horizontal vertical vertical | * /
background-repeat: repeat space;
background-repeat: repeat repeat;
background-repeat: round space;
background-repeat: no-repeat round;

background-repeat: inherit;Copy the code

Example:

Background-origin specifies the origin of the background image. It has three values:

background-origin: border-box
background-origin: padding-box
background-origin: content-boxCopy the code

When background-attachment is fixed, this property will be ignored and will not take effect.

The background-attachment property determines whether the position of the background image is fixed within the viewport or scrolls along the block containing it. It also has three values:

background-attachment: scroll; /* Indicates that the background is fixed relative to the viewport. Even if an element has a scrolling mechanism, the background does not scroll with the content of the element. * /
background-attachment: fixed;  /* Indicates that the background is fixed relative to the content of the element. If an element has a scrolling mechanism, the background will scroll along with the content of the element, and the drawing and positioning areas of the background are relative to the scrollable areas rather than the borders that contain them. * /
background-attachment: local;  /* Indicates that the background is fixed relative to the element itself, rather than scrolling with its content. */Copy the code

The last property is background-size, which sets the size of the background image. Images can keep their original size, stretch to a new size, or scale to the size of the element’s available space while keeping their original proportions.

/* Keyword */
background-size: cover
background-size: contain

/* a value: This value specifies the width of the image. The height of the image is implicitly auto */
background-size: 50%
background-size: 3em
background-size: 12px
background-size: auto

/* Two values */
/* The first value specifies the width of the image, and the second value specifies the height of the image */
background-size: 50% auto
background-size: 3em 25%
background-size: auto 6px
background-size: auto auto

/* Comma-separated multiple values: set multiple backgrounds */
background-size: auto, auto     /* Different from background-size: auto auto */
background-size: 50%, 25%, 25%
background-size: 6px, auto, contain

/* Global attributes */
background-size: inherit;
background-size: initial;
background-size: unset;Copy the code

The sample

Note: areas of the background that are not covered by the background image will still show the background color set with the background-color property. In addition, if the background image is set to transparent or translucent, the background color behind the background image will also be displayed.

Xiii. Fonts

The font property is shorthand for the following properties:

  • font-family
  • font-weight
  • font-stretch
  • font-style
  • font-size

They set the font, weight, italic, and size of the page text, respectively.

Let’s take a look at each of these attributes starting with ‘font-‘.

Font-family allows you to set the font for selected elements by giving a sequential list of font names or font family names.

.serif {
    font-family: Times, Times New Roman, Georgia, serif;
}
.sansserif {
    font-family: Verdana, Arial, Helvetica, sans-serif;
}
.monospace {
    font-family: "Lucida Console", Courier, monospace;
}
Copy the code

Property values are separated by commas. The browser selects the first font in the list that is installed on the computer, or a font that can be downloaded directly as specified by @font-face.

Common font family names are an alternative mechanism for giving a better font when the specified font is not available. Common font family names are keywords, so they cannot be quoted. There should be at least one common font family name at the end of the list. The following are the possible values for this attribute and their definitions.

  • Serif

    A serif type with a special decorative line or serif at the end of a stroke. For example: Lucida Bright, Lucida Fax, Palatino, “Palatino Linotype”, Palladio, “URW Palladio”, Serif.

  • Sans-serif fonts, that is, fonts with smooth stroke endings. For example, “Open Sans”, “Fira Sans”, “Lucida Sans”, “Lucida Sans Unicode”, “Trebuchet MS”, “Liberation Sans”, “Nimbus Sans L”, Sans-serif.
  • Monospace is a font in which every word is the same width. Examples are “Fira Mono”, “DejaVu Sans Mono”, Menlo, Consolas, “Liberation Mono”, Monaco, “Lucida Console”, Monospace.
  • A cursive font. Some of these fonts have cursive or special italic effects. Because this type of font has a little bit of a penmanship effect, it can give people a feeling of handwriting. For example,” Brush Script MT”, “Brush Script Std”, “Lucida Calligraphy”,”Lucida Handwriting”, “Apple Chancery”, cursive.
  • Fantasy Fantasy fonts are mainly those that have special artistic effects. Examples are Papyrus, Herculanum, Party LET, Curlz MT, Harrington, Fantasy.

The font-weight property specifies the size of the font. You can use these keywords:

  • normal
  • bold
  • Bolder (relative to parent)
  • Lighter (relative to the parent element)

You can also use numerical values:

  • 100
  • 200
  • 300
  • 400 is the same thing as normal
  • 500
  • 600
  • 700 is the same as bold
  • 800
  • 900

100 is the thinnest font and 900 is the thickest font.

These values are not supported by every font. If the specified values are not available, use the following rules to determine the actual rendered text:

  • If the specified value is between 400 and 500 (inclusive) : Finds available values between the specified value and 500 in ascending order; If no match is found, the available value less than the specified value is searched in descending order; If no match is found, the available values greater than 500 are searched in ascending order.
  • If the specified value is less than 400, the available values are found in descending order. If no match is found, the available value greater than the specified value is searched in ascending order (first as small as possible, then as large as possible).
  • If the specified value is greater than 500, the available values greater than the specified value are found in ascending order. If no match is found, the available values less than the specified value are searched in descending order (first as large as possible, then as small as possible).

The above policy means that if a font has only two thicknesses to choose from, normal will be used when you specify 100-500, and Bold will be used when you specify 600-900.

The font-style property allows you to set fonts to an italic style.

font-style: normal;
font-style: italic;
font-style: oblique;Copy the code

Italic and OBLIQUE represent italics of text. The differences between them are subtle and italic is often used.

The font-size property specifies the font size.

Because the value of this attribute is used to calculate em and EX units of length, changing this value may change the size of other elements.

Font size supports two types of values:

  1. Length values, such as px, EM, REM, etc., and percentage values.
  2. Keyword values, including:

    • xx-small
    • x-small
    • medium
    • large
    • x-large
    • xx-large
    • Smaller (relative to parent)
    • Larger (relative to parent)

Example:

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

Load a custom font using @font-face

@font-face allows you to add a font from a remote server or from the user’s local location. The font will be automatically downloaded by the browser and used on the page.

@font-face eliminates the need for fonts on the user’s computer. For example, we refer to a third-party font called “MyHelvetica” :

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
  local("HelveticaNeue-Bold"),
  url(MgOpenModernaBold.ttf);
  font-weight: bold;
}Copy the code

The local() function looks up the specified font name locally from the user, and if a match is found, the local font is used. Otherwise, the browser downloads the font resource using the address specified by the URL () function.

Font referenced via @font-face supports the following formats:

  • woff (Web Open Font Format)
  • Woff2 (Web Open Font Format 2.0)
  • eot (Embedded Open Type)
  • otf (OpenType Font)
  • ttf (TrueType Font)

The following properties allow us to define the style of the font to load:

  • font-family
  • font-weight
  • font-style
  • font-stretch

One tip: @font-face references to third-party fonts will depend on the network and load performance will be different for different networks. We must take this into account when developing.

Xiv. Typesetting

In this section, we will discuss the following attributes:

  • text-transform
  • text-decoration
  • text-align
  • vertical-align
  • line-height
  • text-indent
  • text-align-last
  • word-spacing
  • letter-spacing
  • text-shadow
  • white-space
  • tab-size
  • writing-mode
  • hyphens
  • text-orientation
  • direction
  • line-break
  • word-break
  • overflow-wrap

text-transform

The text-transform property transforms the case of text. It has four values:

  • Capitalize: Capitalize the first letter of each word.
  • Uppercase: uppercase all text.
  • Lowercase: lowercase all text.
  • None: Disables converting text case to avoid inheriting attributes.

Here’s an example:

Of course, this property makes no sense for Chinese, which is case-insensitive.

text-decoration

The text-decoration property is used to add decorative effects to the text, including:

  • -Leonard: Underline?
  • -Leonard: Overline
  • Line-through: deletes a line
  • Blink: flashing
  • None: Nothing

You can also set the style and color of the decorative effect.

Such as:

The available style values are: solid (solid line), double (double solid line), dotted (dashed line), bounding (dashed line), wavy (wavy line).

The text-decoration property is actually a short form of text-decoration line, text-decoration color, and text-decoration style.

text-align

Text-align defines how inline content (such as text) is aligned relative to its block parent. Text-align does not control the alignment of the block element itself, only its inline content.

The values supported by this property are:

  • Start: The default value, left if the content direction is left to right, and right if it is not.
  • End: Equal to right if the content direction is left to right, and left otherwise.
  • Left: Line content is aligned to the left.
  • Right: Line content is aligned to the right.
  • Center: Center the contents in the line.
  • Justify: Text is aligned to the side, does not justify the last line.
  • Context-all: is consistent with justify, but forces the last line to be aligned.

Example:

vertical-align

The vertical-align attribute is used to specify the vertical alignment of inline or table-cell elements.

The vertical-align attribute can be used in two environments:

  • Aligns the inline element box model vertically with its inline element container.
  • Align table cell contents vertically.

You cannot use it to align block-level elements vertically.

The vertical-align attribute supports a number of values:

  • Baseline: The default value, aligning the element’s baseline with the parent element’s baseline.
  • Sub: Aligns the element baseline with the subscript baseline of the parent element.
  • Super: Aligns the element’s baseline with the superscript baseline of the parent element.
  • Top: Aligns the top of the element and its descendants with the top of the entire line.
  • Text-top: Aligns the top of the element with the top of the font of the parent element.
  • Middle: aligns the middle of the element with the baseline of the parent element plus half of the x-height of the parent element.
  • Bottom: Aligns the bottom of the element and its descendants with the bottom of the entire line.
  • Text-bottom: Aligns the bottom of the element with the bottom of the font of the parent element.

Example:

line-height

The line-height property is used to set the amount of space for multi-line elements, such as the spacing between multiple lines of text. For block-level elements, it specifies the minimum height of the element’s line boxes. For non-substitute inline elements, it is used to calculate the height of the line box.

The line-height attribute is specified as any of the following:

  • A digital
  • A length of
  • A percentage
  • Keyword normal.

Example:

text-indent

The text-indent property sets the indentation of the first line of a paragraph.

Such as:

p {
  text-indent: -10px;
}Copy the code

text-align-last

By default, the last line of text in a paragraph is aligned according to text-align, and you can change its alignment using the text-align-last attribute.

Such as:

p {
  text-align-last: right;
}Copy the code

word-spacing

Set the spacing between words.

Such as:

p {
  word-spacing: 2px;
}
span {
  word-spacing: -0.2 em;
}
.a {
  word-spacing: normal;
}Copy the code

letter-spacing

Sets the spacing between characters.

Such as:

p {
  letter-spacing: 0.2 px.;
}
span {
  letter-spacing: -0.2 em;
}
.a {
  letter-spacing: normal;
}Copy the code

text-shadow

The text-shadow attribute adds a shadow to the text. You can add multiple shades for text and text-decorations, separated by commas.

Each shadow has two or three <length> parameters, and a <color> parameter related to the shadow color. The first two <length> parameters are the values of X-axis <offset-x> and Y-axis <offset-y> respectively. If there is a third <length> parameter, the third value is the value of the radius of the shadow effect <blur-radius>.

If a <color> color is not specified, the shadow uses a text color.

Example:

white-space

The white-space attribute is used to handle whitespace in elements.

The values that will merge whitespace are:

  • Normal: The default value. Consecutive whitespace characters are merged and newlines are treated as whitespace. When filling the line box, wrap it if necessary.
  • Nowrap: As with normal, successive whitespace characters are merged. But a newline inside the text is invalid.
  • Pre-line: Consecutive whitespace characters are merged. Line breaks occur when a newline character or element is encountered, or when a line box needs to be filled.

Values that will leave blank are:

  • Pre: Successive whitespace characters will be preserved. Line breaks occur only when a line break or element is encountered.
  • Pre-wrap: Successive whitespace characters are retained. Line breaks occur when a newline character or element is encountered, or when a line box needs to be filled.

The following table summarizes the behavior of various white-space values:

tab-size

Sets the TAB width. The default value is 8, which can be changed by an integer or length value.

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

writing-mode

Defines whether the text lines are arranged horizontally or vertically, and the direction in which the text of block-level elements is prevented from progressing.

Available values are:

  • Horizontal-tb: default value
  • Vertical-rl: The contents are arranged vertically. The new line is placed to the left of the previous line.
  • Vertical-lr: The contents are arranged vertically. The new line is placed to the right of the previous line.

direction

Direction Indicates the horizontal direction of text and columns. RTL stands for right to left (similar to Hebrew or Arabic) and LTR stands for left to right (similar to Most languages like English).

Example:

word-break

The word-break property specifies how to break lines within a word. There are three values:

  • Normal: The default value, meaning that text is broken only between words, not within words.
  • Break-all: The browser can break anywhere (but without adding a hyphen).
  • Keep-all: mainly used for CJK (Chinese/Japanese/Korean) texts, continuous lines.

Example:

15. Border

The border property is a shorthand property for setting a border for an element. The border is between the margin and padding elements.

Border can be used to set the value of one or more of the following properties:

  • border-style
  • border-color
  • border-width

Border-radius sets the rounded corner of the element’s border.

You can also use the image as a border by using the border-image attribute or its various independent attributes:

  • border-image-source
  • border-image-slice
  • border-image-width
  • border-image-outset
  • border-image-repeat

Example border property:

Let’s look at each of the attributes of the border in detail, starting with border-style.

Border style

Border-style is a shorthand attribute that sets the style of an element’s border. Supported styles are:

  • Dotted: dot
  • Dashed: the dotted line
  • Solid: solid line
  • Double: indicates a double solid line
  • Groove: Sculpting effect
  • Ridge: Emboss effect
  • Inset: Fall into effect
  • Outset: Highlights the effect
  • None: The default, no border is displayed
  • Hidden: Do not show the border

Example:

Border-style defaults to None, which means that if you change only border-width and border-color the border will not appear unless you also change this property to a value other than None or hidden.

Border-style is a shorthand for four attributes:

  • border-top-style
  • border-right-style
  • border-bottom-style
  • border-left-style

You can use these four properties to change the style of an edge.

Width of border

The border-color property sets the border width of the element.

You can use keyword values:

  • thin
  • Medium (default)
  • thick

Or use px, EM, REM units or some other number for length.

Border-width is also a shorthand for the following four attributes:

  • border-top-width
  • border-right-width
  • border-bottom-width
  • border-left-width

Color of the border

The border-width property sets the border color of the element.

If you do not set the color of the border, by default the border uses the color of the element’s text.

Code examples:

/* border-color: color; Single-valued syntax */ 
border-color: red;

/* border-color: vertical horizontal; Double-valued syntax */
border-color: red #f015ca;

/* border-color: top horizontal bottom; Ternary syntax */
border-color: red yellow green;

/* border-color: top right bottom left; Four-valued syntax */
border-color: red yellow green blue;

border-color: inheritCopy the code

Similarly, border-color is a shorthand property:

  • border-top-color
  • border-right-color
  • border-bottom-color
  • border-left-color

Border with rounded corners

The border-radius attribute allows you to set the rounded edges of the element’s borders. Identify a circle when using one radius and an ellipse when using two. The intersection of this circle with the border creates a rounded corner effect.

Schematic from MDN:

Example:

The principles and techniques of the border-radius attribute are hard to explain in a few words. For a more detailed analysis, you can read the article “When is the Autumn Moon? How much do YOU know about CSS3 border-radius?”

border-image

The final border property is also one of the cool ones in CSS. Border-image allows you to draw an image around the border of an element, which makes it much easier to draw complex look-and-feel components. When using border-image, it replaces the border style set by the border-style property.

Setting the border image requires setting the following five properties:

  • border-image-source
  • border-image-slice
  • border-image-width
  • border-image-outset
  • border-image-repeat

Border-image is a shorthand for these five attributes.

Example: the HTML

<div id="bitmap">The image is stretched and filled with the border area.</div>Copy the code

CSS

#bitmap { 
  border: 30px solid transparent;
  padding: 20px;
  border-image: url("https://mdn.mozillademos.org/files/4127/border.png") 30;
}Copy the code

For a more detailed explanation of the principle of the border-image attribute, please read the “Border-image Border Image in Detail”.

16. Margin

The margin attribute is used to add margins to elements in four directions.

Please remember:

  • Margin Adds space to the border of an element
  • Padding adds space to the border of the element

Margin is short for the four margin property Settings. The four margin property Settings are:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

They are very simple to use, for example:

margin-left: 30px;
margin-right: 3em;Copy the code

Magin shorthand

Margin is a shorthand attribute that takes 1 to 4 optional parameters, with different numbers of parameters representing different meanings:

  • A value that will be assigned to all four edges.

    margin: 20px;Copy the code
  • Two values. The first value is matched for up and down, and the second value is matched for left and right.

    margin: 20px 10px;Copy the code
  • The first value is matched to the top, the second value is matched to the left and right, and the third value is matched to the bottom.

    margin: 20px 10px 30px;Copy the code
  • The four values are matched in the order of top, right, bottom, and left (that is, clockwise).

    margin: 20px 10px 5px 0px;Copy the code

The type of value accepted

The margin attribute accepts any unit of length, the most common being PX, EM, REM, and percentage, as well as an auto.

Use auto to center elements

Auto allows the browser to calculate margins automatically, and is most commonly used to center block elements.

margin: 0 auto;Copy the code

In modern browsers, if you want to center something horizontally, use display:flex; justify-content: center;

However, in some older browsers, such as IE8-9, these are not available. To center an element within its parent, use margin: 0 auto.

Using negative margin

Margin can be negative and useful. Setting a negative top margin causes the element itself to move up, and if given a large enough negative value, it will be moved off the page.

Placing a negative margin on an element causes the element below it to move up.

A negative right margin pushes the content of an element beyond its allowable content area.

A negative left margin moves the element to the left, and if given a large enough negative value, it moves off the page.

For more details on negative margin, please go to “Understanding Margin Negative in CSS”.

17. Padding

The padding property is used to add an inner margin to an element in four directions (top, bottom, left, and right).

Please remember:

  • Margin Adds space to the border of an element
  • Padding adds space to the border of the element

Padding is short for four padding property Settings. The four inner margin property Settings are:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

The padding area refers to the space between the content of an element and its boundary. It’s very simple to use:

padding-left: 30px;
padding-right: 3em;Copy the code

This attribute cannot be negative.

Padding shorthand

Padding is a shorthand attribute that takes 1 to 4 optional arguments. Each number of arguments has different meanings:

  • A value that will be assigned to all four edges.

    padding: 20px;Copy the code
  • Two values. The first value is matched for up and down, and the second value is matched for left and right.

    padding: 20px 10px;Copy the code
  • The first value is matched to the top, the second value is matched to the left and right, and the third value is matched to the bottom.

    padding: 20px 10px 30px;Copy the code
  • The four values are matched in the order of top, right, bottom, and left (that is, clockwise).

    padding: 20px 10px 5px 0px;Copy the code

The type of value accepted

The padding property accepts any unit of length, the most common being PX, EM, REM, and percentage.


End of first half, to be continued…

If you require a Word/PDF version of this article, please:

Reference: 1. developer.mozilla.org/zh-cn/docs/… 2. www.ruanyifeng.com/blog/2017/0… 3. www.cnblogs.com/mofish/arch… 4. 5. medium.com/free-code-c blog.shihshih.com/css-filter/…