At the end of 2020, I feel very honored to talk about CSS with a group of outstanding college students. Thank you very much to alibaba Group. Front-end trainee program) for giving me such an opportunity, I also want to thank my good friends Yubo, Mo Ran for their encouragement and support. At the end of the live broadcast, I said THAT I would sort out a text version later. Due to my new transfer to the Team (the interactive Team was transferred to the F(X) Team) and my laziness, I just started to sort out the text version today. Fortunately, it can be completed at the end of the year, but also a remedy. I hope that the following content will be helpful to those who are new to CSS or interested in CSS. I also hope that more students can participate in the Study of Alibaba Group trainee program and gain something from it.

It still feels different live

Although I have attended some front-end industry conference sharing before, this is the first time in my life that live streaming is different. First, I don’t have this experience, and second, I prefer the feeling of offline meeting, because I can be with everyone and have eye contact. It is a kind of support, encouragement, exercise and happiness.

In the front-end community, I’m often referred to as “The Desert.” I personally like CSS, and I have been working in this area for nearly a decade, with little success, but some small gains. I like to write blogs, watch movies, listen to music and so on.

Published a book on CSS in 2014:

It seems that there is no printing now, the net seems to have not stopped selling, but the content is a bit old, but still not out of date!

I have been working in Amoy Interactive for five years and recently joined Amoy Front-end Technology F(X) Team

F(x) Team, F(x) refers to the function F(x), which is a common symbol in machine learning. The essence of deep learning is to find the optimal solution of F(x). It means that members with different characteristics will find the optimal solution of the front-end intelligent team through continuous “training” through the magic effect of fx team.

I’m going to talk to you about

Next, I will talk with you about the six aspects of today’s topic.

Demystify the CSS

Ever since Tim, the creator of the World Wide Web, in 1994. It’s been decades since Berners-Lee founded the World Wide Web (W3C) at the Massachusetts Institute of Technology. You may be wondering what the first web page looked like:

It’s a million miles from the Web pages you see today. It’s true that at the time, there was no style for Web pages, and all Web pages did was deliver information. To put it more simply, it has only words and images, and no other information elements.

People always wanted to be beautiful, and even in those days, people wanted to make their Web pages look good. That same year (1994), Haken. Cascading HTML Style Sheets (CHSS) from Wim Lay:

Add attributes to HTML tags such as BGColor and Face, as well as similar tags to set text styles.

Few people today have touched, or written about, a Web page. Personally, I haven’t used these things to build Web pages, but I’ve seen a lot of pages look like this. I didn’t know at the time that this technique had its own technical term, CHSS (Cascading HTML Style Sheets). Although these tags and attributes to page elements have some personalized UI effects, such as change the text color, font, background color, but written as it is painful for Web developers, especially for a complex, large Web applications, this way to beautify the Web page, will definitely make you miserable.

If nothing else, it makes the code more difficult to maintain and bloated. There is no flexibility, no scalability, no usability.

We Web developers are lucky. As recently as 1994, Hakon. Wim Lay and Bert. Persia collaborated to design CSS and presented CSS proposals at a conference in Chicago. It was also the first time CSS appeared in the eyes of Web developers (though, at the time, there was no such title). And two years later, the CSS 1.0 specification came out:

After two years of development, there was CSS2.0, and after that, there were iterations of CSS 2.1 and CSS 2.2. Meanwhile, the CSS 2.1 specification has guided Web developers to write CSS for years. It wasn’t until later, around 2015, that the W3C’s CSS working Group noticed that CSS was evolving faster and faster, with more features being added and different features advancing at different speeds. At this time, the CSS working Group of the W3C decided not to manage CSS by version numbers, such as CSS1.0, CSS2.0, and CSS2.1, in order to better maintain and manage the features of CSS. Instead, we divide each CSS feature into separate functional modules and manage the features in the CSS specification at Level 1, Level2, and Level 3:

As shown in the figure above, even though CSS is moving forward with the split of functional modules, it does not mean that the split of CSS feature modules will soon enter the formal standard specification, just as CSS2.0 has taken a long time to formally enter the standard specification. This is mainly because any CSS feature passes through several stages to become a true specification:

  • Edit Draft (ED) : Initial stage, very rough
  • First public Working Draft (FPWD) : First public release, beginning to receive group feedback
  • Working draft (WD) : Incorporating feedback from workgroups and the community, early browser implementations usually start at this stage
  • Candidate Recommendation specification (CR) : a relatively stable version suitable for implementation and testing
  • Nominated recommendation specification (PR) : Final opportunity for W3C member companies to voice objections to this specification
  • Formal Recommended Specification (REC) : The final stage of a W3C technical specification

By this time you may be getting a sense of how long it takes for something to become an official specification. In addition to the W3C specification organization’s own problems, this lengthy process also has client vendors supporting different features for their own benefit. It’s also a problem for those of us who are Web developers, because you’re more likely to be the users or evangelists of CSS features than the promoters. Few of us Web developers in China are directly involved in developing, discussing and promoting CSS features.

The term CSS4 began to be used in the community when the CSS selector Level4 module came out. In fact, @RachelAndrew gave the community a voice back in 2016 with “Why There Is No CSS4-Explaining CSS Levels” :

On Github @Jen Simmons has a separate CSS4-related post on CSSWG Drafts, and some of the biggest names in the community weigh in on the topic:

  • Why Are We Talking About CSS4?
  • There Is No Such Thing As CSS4
  • Why There Is No CSS4: Explaining CSS Levels
  • Where Is CSS4? When Is It Coming Out?
  • CSS4: La Nueva Version de CSS que Nunca existira

The above mainly and you talk about the history of CSS and her development process.

After talking about CSS development, let’s talk about the current state of CSS. From the 2019 and 2020 STATUS of CSS reports, we can see the current status of CSS development:

The report is relatively detailed:

In addition to the CHARACTERISTICS of CSS, units and selectors, methodology, framework, tools, environment and other statistics, but also the use of CSS and the status quo is also described, such as:

In addition to the CSS status report, there is also the annual Web Yearbook on CSS survey statistics:

In addition, there are other research reports that also have some CSS-related reports, but none are as detailed or targeted as the CSS Status development report. If you’re looking at other reports on CSS, check out the reports listed in @Geoff Graham’s 2020 Roundup of Web Research:

What is CSS?

CSS is called cascading Style Sheets, an acronym for Cascade Style Sheets. Each letter has a different meaning:

  • C (Cascade) : Refers to cascading. In the CSS, style rules are written one by one, which can be simply understood as the sequence
  • S (Style) : The first S, which refers to Style rules such as body{color: red}
  • S (Sheets) : the second S, it refers to the style sheet, which is what we call.css files, and the CSS code will be placed in the style sheet

Web developers know that a Web page or Web application consists of HTML, CSS, and JavaScript:

Each part plays a different role in the Web:

  • HTML: The backbone of a Web application
  • CSS: Is used to beautify the Web
  • JavaScript: Used to control interaction within Web elements

Today, a Web application or Web page is composed of HTML, CSS and JavaScript, but also a new part, namely WAI-aria:

Wai-aria is part of the Web Accessibility (A11Y) specification to help us build a more accessible Web application.

For those of you who are new to CSS, you will certainly be curious about how CSS works. To be clear in detail, there are many things involved, which are not related to the workings of the browser content. It’s not my area of expertise, so I’m just going to throw some light on it.

As mentioned earlier, a Web page consists of at least three parts: HTML, CSS, and JavaScript. HTML is converted from HTML structure to DOM Tree by HTML Parser. The CSS Parser transforms the CSS into a CSSOM Tree, as shown in the following figure:

The DOM tree and the CSSOM tree will build the render tree:

The final rendering of the Web page as we see it takes a few steps:

If you add AOM (accessible tree) to the mix, it looks something like this:

That’s a bit of a departure from what we’re talking about today. If you don’t want to know too much about the process, simply write: “CSS styles need to be used in conjunction with the corresponding HTML elements before they can be rendered in the browser and presented to the user.”

Personally, I prefer to refer to CSS as tangram or building blocks:

We can achieve the same effect in many different ways.

Because of this, many students find CSS annoying:

CSS is simple, but not easy

@Jeremy Keith said this at CSS Day 2017:

The general meaning is:

Unlike programming languages, CSS has no looping, logic, or other concepts. It is a declarative language, so CSS is easy to learn. Perhaps because of this, it has gained a reputation for simplicity. It’s simple in the sense of “uncomplicated,” but that doesn’t mean it’s easy. Mistaking “easy” for “easy” only hurts.”

There is a debate on Twitter and in the community about this topic:

Sometimes on Twitter you feel like the whole front end of the world is showbiz!

So why all this debate? So LET me give you my own perspective on this.

First picture:

It’s pretty simple in terms of CSS syntax rules and the use of attributes, because you just need to know which element in the HTML is selected and what attributes and values are applied to it. It should be displayed in the browser, for example:

body {
    color: #fff;
    background-color: #09f;
}
Copy the code

A few simple lines of CSS above will give you a white word on a blue background in your browser:

There is no need to keep all the CSS properties and their values in mind, because there are many ways to look them up. For example, MDN has a list of CSS properties:

This is the main reason why CSS is simple.

So why is CSS not easy? There are a number of reasons for this, but let’s start with what everyone thinks is a simple rule of CSS:

<div class="card">1</div>

<div class="card__news">2</div>

.card {
    width: 100px;
}

.card.card__news {
    width: 100%;
}
Copy the code

Imagine, what is the width of these two divs? Can you be confident enough to say the right answer immediately when you see the code above? If your mental answer is the same as your own, then congratulations, you have some knowledge of CSS, at least not a beginner. So continue to look at this example:

<div class="a">Text</div>
<div class="b">Text</div>
<div class="a b">Text</div>
<div class="b a">Text</div>

.a {
    color: red;
}

.b {
    color: blue;
}

.a.b {
    color: orange;
}

.b.a {
    color: yellow;
}
Copy the code

What is the text color text of the four divs? I remember @Max Stoiber wrote a similar questionnaire on Twitter:

This is a problem that can confuse a lot of students. In addition, there are a number of basic concepts in CSS that can help you not find CSS easy, such as:

  • cascading
  • inheritance
  • The weight
  • Visual formatting model
  • The box model
  • layout
  • Style maintenance
  • , etc.

Each of the basic concepts listed above would require one or more lengthy articles to fully explain. So I can only throw a brick to attract jade for everyone here, and attach the link of relevant knowledge point on the corresponding content more. If you are interested, you can click on the corresponding link for further reading.

CSS cascade

As explained above, Cascade means “Cascade”, which might be easier to understand with an example. For example, in a style.css style file, we write two style rules for the same element:

<a href="#" class="link">Link</a>

a {
    color: #90f;
}

.link {
    color: #f36;
}
Copy the code

A comes before.link, which is the order in which style rules for the same element appear, known as cascading.

In fact, cascading in CSS is more complex than this. In addition to the order in which style rules appear in the previous example, there is another kind of cascading that involves other concepts of CSS, such as:

  • Document Flow (Normal Flow)
  • Formatting Context
  • Stacking Context
  • Stacking Level
  • Stacking Order

For this reason, I’ve divided CSS cascading into two parts:

Let’s start with the first part.

The document flow

Document flow is a fundamental and important concept in CSS. It is often referred to as a Document Flow, but the CSS standard is called a Normal Flow, which means Normal Flow or regular Flow. People prefer to call it document flow. What about CSS document flow?

Any element in HTML is really just an object and a box. By default, it is arranged in the order in which it appears, and that order is document flow.

Document flow is one way in which elements are rendered on a Web page. All HTML elements are Block Boxes (block-level elements) or Inline Boxes (Inline elements). When a browser starts rendering an HTML document, it starts at the top of the window and allocates the space needed for elements throughout the document’s content. Unless the size of the document is limited by CSS rules, the browser extends the document vertically to accommodate the entire content. Each new block-level element is rendered as a new row. Inline elements are rendered horizontally in order until the current line hits a boundary, and then the next line is rendered vertically.

In fact, Boxes in normal document flow belong to a type of Formatting Context, known as Block Formatting Context and Inline Formatting Context. One caveat, though, is that they can only be one or the other, but not both. By implication, any HTML element that is rendered is a Box, and these boxes are either block boxes or inline boxes. Even text that is not wrapped in any element can be an anonymous block box or inline box, depending on the situation.

The formatting context limits the scope of the element box, similar to the width and height limits. If understood in this way, ordinary flow is a process like this:

  • In the context of block formatting, block-level elements Stack vertically from top to bottom in their container box, in the order they appear in the HTML source, and occupy a single line, bounded by the edge of the parent box. The distance between two adjacent elements is determined by the margin property. Vertical margins Collapse margins within the same block formatting context. The width of block-level elements is not affected by floating elements unless a new block-formatting context is created.
  • In the corresponding inline formatting context, the inline elements are arranged horizontally, one after the other, starting at the top of the container.

With all that said, the simple description is: how to arrange HTML elements. Take an example of a normal document flow with block formatting context, as follows:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
Copy the code

The corresponding effect is as follows:

Formatting context

Formatting context has been mentioned several times before. In CSS, formatting context refers to:

The environment defined by the initial element

There are two main points, one is the environment of the element definition and the other is initialization.

We use the display property of CSS to format elements, creating a formatting context.

After using display to format the elements, you can place the contents in different containers, just like in our daily life, different containers can see different effects:

Let’s look at a simple listing:

The biggest difference in the figure above is that ul on the left does not explicitly set display: contents; Ul on the right explicitly sets display: contents, which changes the original format, that is, its child li becomes a grid item. The difference between the two effects is as follows:

Cascading context

The HTML document we usually see from the device terminal is a flat, in fact, the HTML document elements exist in three dimensions. In addition to the familiar x and Y axes of the flat canvas, there is the Z axis, which controls the third dimension.

The x and y axes are easy to understand, one goes to the right and one goes down. But the Z-axis is a little harder to understand. Make sure that elements are arranged along the Z-axis in CSS, which represents an invisible vertical line between the user and the screen:

The system consists of a three-dimensional Z-axis in which the elements are Stacked. The z axis points to the viewer, the X axis points to the right of the screen, and the Y axis points to the bottom of the screen.

Typically, browsers place elements in a specific order specified in the CSS specification:

The element that appears first in the DOM tree is placed first, and the element that appears later is placed above the previous element. But it’s not always that easy. This works only if all elements on the page flow naturally. That is, it works when no element in the flow has been changed or has left the document flow.

In fact, every HTML element belongs to a cascading context. Each positioned element in a given cascading context has a cascading level of integers, and boxes of elements with larger stack levels are always preceded (above) boxes with lower stack levels. Boxes may have a negative cascade level. Boxes with the same stack level in the cascading context are stacked together according to the order in which they appear in the document tree.

A cascading context in a document is formed by an element that satisfies any of the following criteria:

  • The root element ()
  • The position whose z-index is not auto is non-static
  • The value of position is non-static
  • A z – the index values are not for auto Flex project (Flex item), i.e., the parent element display: Flex | inline – Flex
  • An element with a value less than 1 on opacity
  • An element whose transform property value is not None
  • Elements whose mix-blending-mode attribute value is not normal
  • Filter, perspective, Clip-path, mask, and motion-path elements whose values are not None
  • Elements whose perspective value is not None
  • The Isolation property is set to the element of the ISOLATE
  • Arbitrary CSS properties are specified in will-change, even if you don’t specify their values directly

And each page has a default cascading context. The root of this cascading context is the HTML element. Everything in the HTML element is placed on a layer of the default cascading context.

Laminated level

The Stacking Level determines the order in which elements in the same cascading context are displayed on the Z axis. The word “Level” often conjures up images of the world we live in. In the real world, everyone is an individual, including twins, and there are differences. For example, although twins look alike, they are actually born in a sequential order, with the first being the eldest. The same is true of elements in a web page. Each element in a web page is an individual, and they must have a similar ranking. And this ranking sort, according to seniority is what we say here cascade level. The layered level of context elements can be understood as the rank of officials, such as county heads and governors. For ordinary elements, well… Make your own interpretation.

Therefore, it is obvious that all elements have a cascading level, including the cascading context element, and the cascading level of the cascading context element can be understood as the rank of the official, one or two, the head of the county, the governor, and so on. However, the discussion of the level of cascading of ordinary elements is limited to the current cascading context element. Why is that? Because otherwise there’s no point.

The terminology translates to:

The level of a normal element is determined preferentially by the context of the element, so the level comparison is only meaningful in the context of the current element.

It is important not to confuse the cascading level with the Z-index property of CSS. Yes, there are some cases where z-index can affect the level of stacking, but only the positioning element and the child element of the Flex box; At the cascade level, all elements are present.

Stacking sequence

In HTML documents, by default there is a Natural progression Order, which is the Order in which elements are placed on the Z-axis. It is determined by many factors. For example, the following list shows the order in which element boxes are placed in the context of the cascading order, starting at the bottom of the cascading, with seven hierarchies:

  • Background and borders: The background and borders of the elements that form the cascading context. The lowest level in a cascading context.
  • Negative Z-index value: A child element in the cascading context that has a negative Z-index value.
  • Block-level box: Non-inline, non-positioned child element of document flow.
  • Float box: Unpositioned float element.
  • Inline box: Inline level non-positioned child element in a document flow.
  • Z-index: 0: locates the element. These elements form a new cascading context.
  • Positive Z-index value: position element. The highest level in a cascading context.

These seven cascade levels form the rules of the cascade order. Elements on cascading levels 7 appear higher up (closer to the viewer) than those on levels 1-6. A diagram from W3Help helps us understand the seven hierarchical levels better:

In fact, the rules for cascading order are more complicated.

When a page contains floating elements, absolutely positioned elements, fixed positioned elements, or relatively positioned elements (elements offset by a certain amount from their normal position), and inline elements, browsers display them differently (place them). Elements are arranged from nearest to the viewer to farthest, as shown below:

  • Location elements are arranged in order of appearance in the source code. The most recent content in the source code is closest to the viewer
  • Inline elements (such as text and images) are inflow and non-positioning (their position is static)
  • Non-floating elements are arranged in the order they appear in the source code
  • Non-positioned and non-floating block-level elements
  • The root element HTML is the root of the global cascading context and contains all the elements on the page

This is the default cascading order that browsers apply when rendering elements on a page.

If you want to change the rendering order of positioned elements on the Z-axis, use the Z-index property. For example, if you have two absolutely positioned elements that overlap at some point, and you want one element to appear before the other, even if it comes before it in the source code, you can do this using the Z-index attribute.

The first important thing to note at this point is that the Z-index attribute only applies to positioned elements. So, even if you give an element a z-index value and place it before other elements, the z-index will not affect the element unless it is positioned; That is, unless it has a position value other than static.

Therefore, if all positioned elements have an index value of z-index, the elements are arranged from nearest to the viewer to farthest, as shown below:

The positioning element with a positive Z-index. Higher values are closer to the screen. Then, arrange them in the order they appear in the source code:

  • Locate the element’s z-index:0 or z-index: auto;
  • Inline elements, such as text and images, are in-stream and non-positioned (their position is static)
  • Sequential unpositioned floating elements appear in source code
  • Non-positioned and non-floating block-level elements
  • The positioning element with a negative z-index. A lower Z-index value is closer. Then follow the order they appear in the source code
  • The root element HTML is the root of the global cascading context and contains all the elements on the page

When we set the Z-index value on the positioned element, it specifies the order of the element in the cascading sequence context to which it belongs, and it will be rendered on the screen following the steps above.

However, another thing happens when we set the element’s Z-index. An element that takes a Z-index value other than the default auto actually creates a cascading context for all of its positioned descendants. As we mentioned earlier, each cascading context has a root element that contains all of its elements. When you apply the Z-index attribute to this element, it specifies the z-order of the elements in its contained context and also creates a new cascading order context with the element as its root.

A positioned element with a value of Z-index: Auto is treated as creating a new stacked order context, but any positioned descendants and descendants that actually create the new stacked order context are treated as part of the parent, not the new stacked order context.

When an element becomes a new cascading sequence context, the descendant elements it locates will be layered in according to the rules of the element itself we mentioned earlier. So, if we were to rewrite the rendering process again, it would look like this:

  • A cascading sequence context consisting of positional elements with a positive Z-index. Higher values are closer to the screen. They are then rendered in the order they appear in the source code
  • Locate the element’s z-index: 0 or z-index: auto
  • Inline elements (such as text and images) are in-stream and non-positioned (their positions are static)
  • Non-floating elements are arranged in the order they appear in the source code
  • Non-positioned and non-floating block-level elements
  • A cascading sequence context consisting of positional elements with a negative z-index. The lower Z-index values are closer to the screen. They are then rendered in the order they appear in the source code
  • The root element HTML is the root of the global cascading context and contains all the elements on the page

Therefore, when we use the Z-index attribute to determine the order of positioned elements in its cascading order, we also create an “Atomic” cascading order context, where each element becomes the cascading order context for all of its positioned descendants.

Cascading style

Back to the cascade of styles. CSS can write the same style rules in any code block, such as {}, at the same time, for example:

p { color: red; color: blue; /* adopted */}Copy the code

While this writing does not cause errors, it is not recommended to write CSS style rules this way.

As we mentioned earlier, it is possible to use the same style rules for the same element in the same style file, for example:

<a class="link"></a>

a {
    color: red;
}

.link {
    color: blue;
}
Copy the code

Even we can use the same style rules for the same element in different style files, for example

/* base.css */ a { color: red } /* style.css */ @import base.css; a { color: orange; } <! -- index.html --> <link href="style.css" /> <style> a { color: lime; } </style>Copy the code

Each of the above styles can be called cascading styles. However, the rules that are applied to the elements are the same as the rules that appear, assuming that they have the same selector weight.

The weight

When it comes to weights in the CSS field, perhaps we are more concerned with the weight of CSS selectors. In addition to the selector weights that affect the style of an element, it is also related to the order in which CSS style rules appear (as mentioned earlier in the cascading order). And in addition to selector weights, there are also attribute weights.

For selector weights, the following figure can be vividly illustrated:

Selector weights can be similar to survival rules in the Marine world, where big fish eat small fish and small fish eat shrimp. If your implementation does not know the weight of the two selectors, you can also use an online test tool to check:

The weight of a selector will be calculated as follows:

  • If the declaration comes from an inline style (the style property) rather than a selector style rule, count 1, otherwise 0 (=a). In HTML, the style attribute values of an element are style rules, and these attributes have no selectors, so a=1, b = 0, C = 0, d = 0, i.e. 1, 0, 0, 0
  • Count the number of ID attributes in the selector (= b)
  • Count the number of other attributes and pseudo-classes in the selector (= c)
  • Count element names and pseudo-elements in the selector (= d)

The four numbers are joined a-B-C-D (in a number system with a large cardinal number) to indicate particularity, as in the following example:

/ * * {} = 0 b = 0 c = 0 d = 0 - > selector weight = 0,0,0,0 * / li {} / * = 0 b = 0 c = 0 d = 1 - > selector weight = 0,0,0,1 * / li: first - line {} / * = 0 b = 0 C = 0 d = 2 - > selector weight = 0,0,0,2 * / ul li {} / * = 0 b = 0 c = 0 d = 2 - > selector weight = 0,0,0,2 * / ul ol li + {} / * = 0 b = 0 c = 0 d = 3 - > selector weights / h1 + = 0,0,0,3 * * [rel = up] {} / * = 0 b = 0 c = d = 1 - > selector weight = 0,0,1,1 * / ul ol li. Red {} / * = 0 b = 0 c = 1 d = 3 - weight = > selectors 0,0,1,3 * / li. Red. Level {} / * = 0 b = 0 c = 2 d = 1 - > selector weight = 0 #,0,2,1 * / x34y {} / * = 0 b = c = 0 1 d = 0 > selector weight = 0,1,0,0 * / Style ="" /* a=1 b=0 c=0 d=0 -> selector weight =1,0,0,0 */Copy the code

In addition to selector weights affecting element style rules when a client renders a page, the source of the style also affects the element style rules. In terms of the source of CSS rules, there are three main sources of rules:

  • Author rule: This is the CSS declared by the HTML document. That is, we front-end developers write stylesheets that specify the source document according to the conventions of the document language, such as HTML. It’s the only source we can control
  • User: This is defined and controlled by the User of the browser. Not everyone will have one, but when people do add one, it’s usually to cover styles and increase site accessibility. For example, a user can specify a file that sells a style sheet, or a user agent may provide an interface to generate (or behave as if it did) a user style
  • User-agent: These are the default styles that browsers provide for elements. That’s why input looks slightly different on different browsers, and that’s one of the reasons people like to use CSS resets to make sure they override user agent styles, right

These three stylesheets overlap to a certain extent, and they affect each other in a cascading manner.

CSS attributes that apply to the same element also have a weight, such as the same attributes used to describe the element width, min-width, max-width, for example:

In the end, max-width: 100% wins, i.e. the weight of max-width is higher than that of width and min-width, but this is not absolute, and it depends on the scene. But when all three attributes are used on the same element, their weights are roughly as follows:

  • If width is greater than min-width, the value of width is set; When width is less than min-width, the value of min-width is taken
  • If width is greater than max-width, the value of max-width is used; When width is less than max-width, the value of width is taken
  • If min-width is greater than max-width, the min-width value is used as the width of the element; If min-width is less than max-width, the min-width value is used as the width of the element

If you use Flexbox to build Web layouts, there are also certain weight rules for the width of Flex projects:

Start with content ➜ width ➜ flex-basis to decide which to use for the Flex project. If a Flex project explicitly sets the Flex-basis property, content and width are ignored. And min-width is used to set the lower limit of the Flex project; Max-width is used to set the upper limit of a Flex project.

That is:

  • Flex-basis is larger than max-width. The width of a Flex project is equal to max-width
  • If flex-basis is smaller than min-width, the flex project width is min-width, that is, min-width overwrites flex-basis

If min-width is larger than max-width, we can compare the weight of flex-basis with that of min-width. Conversely, if min-width is smaller than max-width, then max-width is used if flex-basis is larger than max-width.

Note that the Flexbox layout has a very complex calculation of the width of the Flex project.

inheritance

Inheritance is another important concept in CSS. In the W3C specification, when describing each CSS property, there is an option called “Inherited”. When the value is “No”, the property is not Inherited, such as the border property on the left. A value of “yes” indicates that the property is inheritable, such as the color property on the right:

CSS provides a mechanism for handling CSS inheritance. Simply put, CSS provides several property values that can be used to handle inheritance of properties. The property values are Initial, inherit, unset, and Revert. In addition to these four property values, there is also an all property value. Although these values are mainly used to help you deal with CSS property inheritance, there are some differences in their use.

That is, CSS layering, weights, and inheritance all have an impact on your CSS. In practical use, if the good use of these concepts and means, can better help you write a lot less style code, and easier to maintain their own CSS code.

CSS cascading, weight and inheritance mentioned here are the basic concepts of CSS, but also the core concepts of CSS, to master or understand these concepts for every Web developer students are very necessary. Only by mastering these concepts can you better understand the CSS and use it correctly.

Visual formatting model

First, a disclaimer:

The visual formatting model and the CSS box model are not the same thing!

Let me put it simply. Whereas Web pages (document trees) are made up of boxes (because any element can be considered a box), the visual formatting model is a set of rules that calculate the rules for converting elements into boxes. The layout of the page is a combination of the locations of these boxes. So by understanding the rules for how elements turn into boxes, you understand how Web pages are laid out. The layout of each box is determined by the following factors:

  • Box dimensions: precisely specified, specified by constraints, or not specified
  • Box types: inline, inline-level, atomic inline-level, and block
  • Location solution: common flow, floating, or absolute location
  • Other elements in the document tree: child or sibling elements of the current box
  • Window size and position
  • The size of the included picture
  • Some other external factor

If you want to fully understand the visual formalization model of CSS, there are a few other concepts that need to be grasped, such as:

  • Block: An abstract concept in which a Block occupies an independent region of a document flow and is stacked vertically on top of one another (by default)
  • Containing blocks: Containing other boxes
  • Box: An abstract concept created by the CSS engine based on the contents of a document. It is used for the positioning, layout, and formatting of document elements
  • Block-level Box: Generated by block-level elements. A block-level element generates at least one block-level box, but it is possible to generate multiple (for example, list item elements)
  • Inline-level Box: Generated by Inline level elements. Similarly, an inline element generates at least one inline box. In-line boxes include in-line boxes and atomic in-line boxes. The difference is whether the box participates in the creation of in-line formatting context
  • Block Box: A Block Box is called a Block Box if it is also a Block container Box. In addition to named Block boxes, there is another class of Anonymous Block boxes, called Anonymous Block boxes, which cannot be selected by CSS selectors
  • Atomic inline-level Box: An in-line Box that does not participate in the creation of the in-line formatting context. Atomic Inline boxes were originally called Atomic Inline boxes, but have since been modified. The contents of intraatomic boxes are not displayed in multiple lines.
  • Line Box: This is different from inline boxes. Row boxes are boxes generated by Inline Formatting Context that represent a row. Line boxes are formatted from one side of the containing block to the other. Typically, browsers create an invisible row box for each row
  • Block Container Box (Block Container Box or Block Containning Box) : A Block Container Box focuses on the current Box as a Container. It does not participate in the layout and positioning of the current Block, but only describes the relationship between the current Box and its descendants
  • Block-level Element: an Element whose display value is Block, list-item, table, Flex, grid, etc., becomes a block-level Element. Whether an element is a block-level element is only an attribute of the element itself and is not directly used for the creation or layout of the formatting context
  • Inline-level elements: An element whose display value is inline, inline-block, inline-table, inline-flex, inline-grid, etc., will be an inline element. As with block elements, whether an element is an inline element is only an attribute of the element itself and is not directly used for the creation or layout of the formatting context
  • Viewport: A Viewport is the Viewport area in the browser. Window size refers to the size of the viewable area of the browser
  • Anonymous box: divided into block anonymous box and line anonymous box. In some cases, visual formatting requires the addition of supplementary boxes that cannot be selected by CSS selectors, called Anonymous boxes.

In addition to the boxes mentioned above, CSS defines several content models that can also be applied to elements. These models are generally used to describe layouts, and they may define some additional box types:

  • Table content model: It is possible to create a table wrapper box and a table box, along with multiple other boxes such as table title boxes, and so on
  • Multi-column content model: It is possible to create multiple column boxes between container boxes and content
  • Flexbox content model: It is possible to create an elastic box
  • Grid content model: A Grid box might be created

These concepts are enough to annoy us. I don’t think you’ll be able to say CSS is easy anymore with these concepts.

With these concepts in mind, let’s talk about formatting contexts in CSS. I’m sure you’ve heard that word at some point. In CSS, there are many kinds of formatting contexts, in addition to the familiar BFC and IFC, there are FFC created by Flexbox layout and GFC created by Grid layout. These are collectively referred to as CSS formatting contexts, also known as visual formatting models. The CSS visual formatting model is the mechanism used to process documents and display them on visual media.

Simply put, it is used to control the position of the box, that is, to achieve the layout of the page.

Formatting context can also be said to be part of CSS visual rendering. Its main function is to determine the layout of the box model, how its children will be positioned, and how they interact with other elements. So understanding the context of CSS formatting helps us grasp the key to various CSS layouts.

Inline formatting context

Inline Formatting Context, or IFC. It is used to format inline boxes.

The height of the IFC’s row box is calculated from the actual height of the element containing the row. The CSS attributes include font size, line-height, vertical-align, and text-align.

The inline elements are arranged horizontally from the top of the containing block, with margin, border, and padding in effect horizontally. Inline elements can be aligned vertically at the top, bottom, or baseline.

When several inline elements do not fit horizontally in a single row Box, they are assigned to two or more row boxes on the vertical stack; therefore, a paragraph is a vertical stack of many row boxes. These row boxes do not separate vertically (unless otherwise specified), and they do not overlap.

  • The vertical-align attribute determines the vertical alignment when the height of the elements in the row is lower than that of the row box.
  • In the horizontal direction, when the total width of the inline elements is smaller than the box, the horizontal division of the inline elements is determined by text-align.
  • Horizontally, when the total width of the row elements exceeds the row box, the row elements are divided into multiple row boxes. If attributes such as non-folding lines are set, the row elements overflow the row box.
  • Both the left and right sides of the row box touch the contain block, and the float element is placed halfway between the row box and the contain fast edge.

Each of these rules creates an inline formatting context:

  • IFC is generated only if a block-level element contains only inline elements
  • The internal boxes will be placed on top of each other in uneven directions
  • The vertical start of these boxes starts at the top of the box containing the block
  • When placing these boxes, the horizontal padding, border, and margin are taken into account
  • In the vertical direction, the boxes may be vertical-align in different ways.
  • All boxes on a row can be completely contained in a Line Box, the width of which is determined by the containing block and the existing float
  • In an IFC, the left and right sides of a row box are generally close to its containing block, but will change due to the presence of floating elements. Floating elements are placed between the IFC and the row box, shortening the width of the row box
  • The horizontal rendering rule is determined by text-align when the total width of the inline boxes is less than the row box containing them
  • When the inline box exceeds the width of the line box, it is divided into multiple boxes, which are distributed among multiple line boxes. If an inline box cannot be split, the row box will overflow

IFC is mainly used for:

  • Line elements are horizontally centered with text-align
  • The inline element is centered vertically by the vertical-align attribute, extending the height of the parent element

Block formatting context

Block Formatting Context (BFC) is part of the visual CSS rendering of a Web page. It is the area where the layout process of Block boxes takes place and where floating elements interact with other elements.

A BFC is essentially a rendered area of the page that is isolated from the rest of the page. The outer elements of the container do not affect the outer elements, and the outer elements do not affect the child elements of the container.

Boxes inside the BFC are arranged from top to bottom, one after the other. The vertical box distance in BFC is subject to the margin attribute, and the upper and lower margins will be superimposed. The left outermost boundary of each element touches the left side of the containing block BFC (for left-to-right formatting, otherwise the opposite). This is true even if there is a float. The BFC region does not fold with the box of floating elements. The height of the BFC is also affected by the floating element, which contributes to the calculation.

The following rules can create a BFC:

  • The root element or the element containing the root element
  • Float element (float of element is not None)
  • Absolute position element (element position is absolute or fixed)
  • Inline block element (element display is inline-block)
  • Table cell (element display is table-cell, HTML table cell default value)
  • Table title (display element as table-caption, HTML table title default to this value)
  • Anonymous table cell element (display table, table-row, table-row-group, table-header-group, table-footer-group) Default properties for row, tBody, thead, tfoot) or inline-table)
  • Overflow values are not visible block elements
  • The element whose display value is flow-root
  • Contain elements whose contain value is Layout, Content, or strict
  • Elastic elements (display is a direct child of flex or inline-flex elements)
  • Grid elements (display is grid or a direct child of the inline-grid element)
  • Multi-column containers (elements with column-count or column-width not auto, including column-count 1)
  • Column-span elements for all always create a new BFC, even if the element is not wrapped in a multi-column container

The block formatting context contains everything inside the element that created it. Its main uses:

  • Create a separate rendering environment
  • Prevent height collapse caused by floating
  • Prevent upper and lower adjacent margins from folding

Flex Formatting Context

Flex Formatting Context is commonly known as FFC. When display is set to flex or inline-flex, a Flexbox container is created. The container creates a new formatting context for its content, the Flex formatting context.

Note, however, that Flexbox containers are not block containers (block-level boxes), and the following properties that apply to block layouts do not apply to Flexbox layouts:

  • The column-* attribute in multiple columns does not apply to Flexbox containers
  • The float and clear properties will not work on Flex projects and will not take Flex projects out of the document stream
  • The vertical-algin attribute will not work on a Flex project
  • ::first-line and ::first-letter pseudo-elements do not apply to Flexbox containers, and Flexbox containers do not provide the first formatted line or first letter for their ancestors

Grid formatting context

Grid formatting Context (GFC) Similar to FFC, a grid container is created when the element’s display value is grid or inline-grid. The completor creates a new formatting context for its content, the Grid formatting context. This is the same as creating a BFC, but with a grid layout instead of a block layout.

Grid containers are not block containers, so some properties assumed to be designed for block layout do not apply in the context of grid formatting. In particular:

  • Float and clear will not work on grid projects. But the float property still affects the computed value of display on the grid completor’s child elements, because this happens before the grid item is determined
  • Vertical-align will not work for grid projects either
  • ::first-line and ::first-letter pseudo-elements do not work with grid containers, and the grid container does not provide them with the first formatted line or the first formatted letter

The box model

In the CSS world, what HTML element can be parsed into a box? You can use CSS properties (physical properties) to determine the size of the box. The box size is determined by four attributes:

  • Content: Text, image, or other media Content in the element
  • Padding: The space between the borders of the box’s contents
  • Border: Border of the box
  • Margin: The distance between the box and other boxes

If we use a graph to describe it, it could look something like this:

The attributes mentioned above are all the browser needs to render the element box. CSSer, for his part, likes to use a box model like the one below to illustrate elements:

And “Computed” in the browser debugger shows how it interprets the box model of an element:

In general, the width of the box is the sum of the content of the element, the inner margin and the border, which is often referred to as the width of the inner box. You can calculate the width of the outer box if you add the width of the outer margin to the width of the inner box.

The height calculation of a box is similar to the width calculation.

But in layout, the width of the box can directly affect the layout, even directly break the layout of the page. For example, a div element:

div { 
    width: 100%; 
    padding: 1rem; 
}
Copy the code

Causes the div to go out of the container, as shown below:

The box-sizing property of CSS helps control the size of the box:

Use an example to make it easier to understand:

Did you notice that the padding, border, and margin mentioned above all use physical properties to describe a box? When developers discuss box models, they usually use the following figure to illustrate it:

But with the emergence of the logical properties of CSS, in addition to the physical properties we are familiar with, CSS also added a lot of logical properties:

Logical attributes will also change the CSS box model:

If you use logical attributes instead of physical attributes in your layout, this can be very useful for international sites such as Arabic-language sites. When changing writing mode, no additional layout related attributes need to be adjusted:

layout

Web layout is a constant topic for Web front-end developers.

As Web technology continues to advance, Web layout related technologies have also evolved in different evolution processes of the Web.

Throughout the evolution of Web layout, we have experienced no layout, table layout, location layout, floating layout, Flexbox layout and other layout modes. Beyond the familiar layouts, there will soon be modern ones such as Grid, Shapes (similar to magazine layouts) and multi-column layouts (similar to newspaper layouts). These layout patterns reflect the evolution of the Web and bear their own destiny at that time.

For Web front-end developers, the layout of the Web always follows the design of the Web page. And the design of web pages in different periods are constantly changing: from the original site to the current popular site in the design of the development of three stages:

The positioning of Web elements has evolved in different design scenarios:

  • Web Design 1.0 is “one-dimensional” : Design elements are mostly sequenced (in the natural order of document flow)
  • Web Design 2.0 is “two-dimensional” : cells have grids for placing elements, with more freedom
  • Web Design 3.0 is a “new dimension” : it can position elements and overlap them as freely as graphic design tools. It opens up new perspectives for web design. It will also usher in a new era of Web page design

It’s more descriptive if we use Lego, as shown in the picture above.

For different stages, the corresponding pattern of Web layout can also be set into the whole design evolution process, if the ape evolution is described, something like the following picture:

In today’s mobile world, we need to target more types of devices. To accommodate more devices, we can also use responsive Web layouts:

But that doesn’t stop the discussion of Web layouts. You may soon need to deal with layout adaptation for foldable devices or multi-screen devices:

The advent of multi-screen and foldable devices is likely to change the way the Web is developed, designed and interacted over the next decade. Also, a CSS specification for these devices is beginning to be drafted.

Posture for writing CSS

Because of the cascade, weight, inheritance and other factors of CSS, many developers always encounter problems such as selector conflicts, style overwriting, and code redundancy when writing CSS. To this end, there are many methodologies for writing or maintaining CSS in the community, such as:

There are also a number of related CSS Frameworks to help you quickly write CSS and build projects:

Especially in the past two years, there has been a lot of discussion in the community about utility-first CSS, and the representative framework in this regard is Tailwind CSS:

Personally, I prefer BEM and Atomic:

Now I like the ** utility-first CSS is Tailwind CSS.

In addition to the CSS methodology and framework, there are many CSS processors in the community to improve your coding efficiency and maintain your CSS projects:

In many cases, Sass, Stylus, and LESS are often referred to as preprocessors, and PostCSS is often referred to as post-processors, which can be said to be one after the other:

Their relationship is shown below:

However, with frameworks like React and Vue, there’s another voice in the community that’s writing CSS in JavaScript (i.e. Css-in-js) :

Through all this, CSS writing and maintenance has changed a lot:

However, no matter what happens, we can find the best way to write CSS like this one. Because there is no best, only the most appropriate:

CSS Is Awesome

@Brandon Smith has a blog post that says CSS is Awesome!

Why is CSS so great (and powerful)? Let me talk about this topic from my own point of view.

CSSer (or Web developer) of a certain age will be familiar with the ZEN garden of CSS. One of the biggest features of CSS Zen Garden is that it can achieve different Web UI effects based on the same set of HTML structure, that is, there are different layout styles:

It is also known as the beauty of CSS design. And there’s a book about it:

If you are interested, try it out and see how many different UI effects you can implement based on the same HTML structure.

Another example of CSS Zen Garden is @Stephanie Eckles’ Style Stage, which uses the same HTML structure to achieve the same UI effect:

I call it the modern zen garden of CSS, the modern beauty of CSS design.

Today, in modern Web development, CSS is becoming more and more powerful, and its role is not only to achieve Web layout, simple UI effects. We can use CSS to implement many complex UI effects in projects:

I call it the visual beauty of CSS.

Using CSS attributes such as border, box-shadow, border-radius, gradient, clip-path, Transform, and mask can be directly used to draw different visual effects and even achieve some complex UI. You can also use CSS transition and Animation to create a UI scene with fretting effects.

Imagine using a div to draw different UI effects. You might be surprised to see the results:

Even more surprisingly, you can draw with CSS:

In China, @Yuan Chuan studies Generative Art With CSS very well. For example, yuan Chuan posted Generative Art With CSS in CSSConf.

By showing you how to use it to draw different works of art, you’ll see the amazing side of CSS and marvel at how close CSS is to creating art:

In addition, CSS has developed very fast in recent years, introducing many new features. For example, @Argyleink shared a topic called “What’s New with CSS?” at the fourth CSS event in London (LondonCSS 2020). , mentioned a number of new CSS features:

As mentioned in the PPT:

  • CSS Custom attributes
  • Logical CSS Properties
  • CSS writing mode
  • The GAP property of the CSS
  • CSS Grid layout, and subgrid
  • CSS scroll capture
  • New media features of the CSS
  • CSS selector Level 4

I’ve compiled a new article on this basis that covers nearly two dozen CSS features.

In addition, when sharing, I also missed a topic, that is CSS Houdini, I am very interested in this aspect. At this year’s GDS Conference, @una Kravets shared a topic on this topic, and also launched Houdini to DC. How website, a collection of CSS Houdini Paint APIS and custom properties building Demo:

In the Demo provided by Houdin.how, we can adjust the values of the custom properties and see different effects:

If you’re interested, you can also submit your Demo to the Github repository.

How to Learn CSS

Next, I will briefly talk about how I learn CSS, only their own point of care, for reference only.

I think no matter what learning knowledge, should be inseparable from books! In terms of CSS, there are a few books that I think you should spend some time reading, such as:

If you’re not a beginner CSSer, the W3C specification documentation on CSS is worth reading:

To be honest, reading norms is a painful thing, but different periods, different stages of reading norms will have different harvest. Like myself, WHEN I reread the specifications this year, I learned a lot. Perhaps reading the specification focuses more on the use of CSS properties, but when I re-read the specification for nearly a year, I focused more on the knowledge of the critical point of property use. In other words, the problems we encounter with CSS are all described and answered in the specification.

In addition to reading the spec, there are many excellent blogs in the community that are worth reading:

In the Chinese community, there are blogs about CSS, especially recommended:

  • Teacher Zhang Xinxu xin space, xin life
  • Chokcoco Teacher’s Love CSS (ICSS)

When you find good blogs or sites in your community, you can also subscribe to them using the RSS app:

RSS is a great tool. It saves you a lot of time, and it is more targeted to get information that you might like.

Need this RSS list, can be private accidentally!

If RSS is not your thing, you can also use some browser extensions, such as Chrome, which I created with a Daily. Dev:

Another way to get information is by subscribing to the Github repository of interest or following some of the industry titans:

There are many channels to obtain information, resulting in high cost of obtaining information. Most of the time, you may see a good topic today and just skim it. You want to read it in depth when you have time, but you can’t find the link to the article at this time. For this reason, I have developed a habit of creating a local Blog in the past two years. One of the columns is to collect the articles I find interesting each month:

It’s all about watching and reading. That’s not enough. We need to write more.

Writing demos, I often write some demos myself on Codepen, whether it’s validation, creative, or practice. I like to write:

In addition to allowing yourself to do exercises on Codepen, you can also see a lot of demos and learn some new knowledge and skills from other people’s demos. If you haven’t already, it’s highly recommended that you start your journey in Codepen.

In addition to writing a Demo is not enough, we should also summarize the knowledge we have learned, and writing a blog is a good way:

I myself tend to categorize questions first:

  • I understand
  • I seem to get it
  • I don’t understand
  • I’m interested

Make lists of all of these so that you can plan to see something, learn something, and write something.

By now, it should be the last day of 2020. Recall that I have been writing blog for ten years since I created W3cplus in 2010, and I have written 1561 articles:

Of course, you might think some of them are useless, but in my case they are all useful. In addition to the habit of blogging, I sometimes summarize my year or phase.

Everyone and everyone will be different, there may be a suitable for their own method, my learning method may be more stupid, simply said that is to read more, write more, ask more, summarize more and so on.

Will AI replace CSSer?

At the end of the year, I changed from the interactive Team I had been in for five years to the Amoy F(X) Team. My new team is working on a technology product, imgCook

You can also find it on Github!

If you’re interested, you can just come and experience the first wave! If you run into any problems with imgCook, you can keep it private!

Finally, I leave a topic for students who are interested in this topic to discuss together:

“Will AI replace CSSer in the near future?”