preface
As a programmer, the implementation and consolidation of technology is necessary, so I thought of writing a series of articles entitled why What or How to explain a problem clearly.
Why What or How chapter 2, What is CSS?
paraphrase
CSS – Cascading Style Sheets
CSS is also a kind of markup language. Its content is input to the browser, and the browser parses its text content as additional style information to the HTML to decorate the tag.
Markup language: a language that describes the structure of a document or the details of data processing in a fixed form, usually in plain text, whose content is used as input to other programs.
Style sheets As you all know, a table of style information, in the form of key-value pairs, has the following format
p {
font-size: 10px;
}
Copy the code
So what is cascading? What’s the point of cascading?
Layering, literally: We know that HTML’s page structure is a tree, with different tags nested hierarchically to form a page. From another perspective, the structure of a page is layer by layer, as shown in the figure below
HTML is the lowest layer, body is above HTML, header, nav, article, aside, footer are above body, section is above article, and the stack of tags forms the structure of the page. So what does this have to do with CSS?
A quick question: If the article tag represents an article, should the size, style, and layout of the text within it be consistent?
Is!!! This is why styles are layered. As soon as I give the article tag a fixed style, the tags inside the article will inherit (in part) the default style information. The hierarchy represents the relationship between nodes, so there is a parent-child distinction and there is an inheritance relationship.
Then some friends will ask? Isn’t that what CSS is now? That’s not the default behavior, right?
This is true of CSS, but not of the style rules that initially embellishment HTML. CSS is just one of many rules that eventually become standard.
history
1991-1993.
In 2000, a variety of browsers emerged, but each implemented its own style rules, web presentation by the user control, there is no uniform style rules.1993
Years,Mosaic
Browser adoption adds a new categoryHTML
The tag implements style expression to meet the designer’s requirements,<FONT></FONT>
Tags representing styles like this start appearing.1994
Years,Håkon W Lie
Put forward cascadeHTML
The stylesheet (Cascading HTML Style Sheets
),CSS
The embryonic form of.1995
Years,W3C
Set up,W3C
对CSS
I was so interested in it that I organized a seminar for it.1996
Years,CSS
Syntax complete, publishedCSS1.0
, but because the mainstream browsers at that time did not support (every family has their own style of writing), and the mainstream way at that time isHTML
The style tag, thereforeCSS
It took a few years to catch on.1997
Years,W3C
Organized a special managementCSS
Working group.1998
Browser market share was lost to Microsoft corpIE4
And NetscapeNetscape Navigator
Two browser giants.IE4
Be the first to achieveCSS 1.0
However, due to the lack of attention, the implementation of the specification is not perfect,bug
A lot of. Because different browsers support different standards, web designers have toIE
和Netscape Navigator
Design a separate set of web pages. Community of civilian designersWeb Standards Initiative (WaSP)
Launch the Marine generalsW3C
The recommendations are promoted as standard and criticized as not yet joinedW3C
Standard industry vendors.1998
Years,W3C
Organization publishedCSS2.0
Web standards are planned7
The members were establishedCSS Samurai
, it is pointed out thatOpera
The browser andIE
Browser supportCSS
There are many problems in…Opera
The company fixed the problem, but Microsoft didn’t. They are also persuading other browsers to start supporting itCSS
Standard.1999
Years,W3C
Began to developCSS3
Standard.2003
Years,Dave Shea
Launched a program calledCSS Zen Garden (CSS Zen Garden)
“Shows that it is possible to take a completely new look at web art simply by applying different page style rules.2006-2009.
Years,DIV+CSS
Layout has gradually replaced the lack of flexibility of the traditional table layout, table-free web design has become the main scheme of web content layout.Since 2009 -
.CSS3
Some of the standards have been published, but they are not yet fully developed, and browser vendors are following suit.W3C
The official classification of these different features is calledmodules
Not in useCSS3.0
The version number will be separatemodule
Name them individually, each of themmodule
There are also different version numbers.- .
It took at least five years for CSS standards to be developed and browsers to be implemented, and for CSS to be adopted by browser manufacturers and by civil society organizations. Until now, we can still use style tags like in HTML, which is also a legacy of history, but with the introduction of HTML5, HTML tags are the structure of web pages, CSS is the style information of web pages, So the style tags have been removed from the specification and should be used sparingly or not at all.
CSS stands out in a large number of style rules, in fact, and the success of IE4 has a lot to do with this, IE series was the first to implement THE CSS1.0 standard, can be said to be one of the factors in the war with Netscape Navigator victory, Even many of the CSS3 attributes have IE’s shadow behind them, but the subsequent fall of the IE series is largely due to its inaction.
Grammar or structure
The structure of a CSS rule is as follows:
┌ ─ ─ ─ ─ ─ ─ ─ selection rules ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ declaration block ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ p + p > span: first - child {┌ ─ ─ ─ ─ ─ ─ CSS properties ─ ─ ─ ─ ─ ─ ─ ┐ the font - size: 10 px; ├ ─ ─ ─ ─ ─ husband!Copy the code
It consists of two parts, selector and declaration block.
- Selection rule: Matches specific items
HTML
The label meets the requirements - Declaration block: Used to style conforming labels
A selection rule has two parts, the selector and the connector. In the above example, p, SPAN, :first-child are the selector, and the + and > symbols are the connector.
A declaration block consists of multiple CSS properties. The properties are divided into two parts: property name and property value. At the end, an attribute specifies a style for the tag.
Selection rules
Selection rules, as the name suggests, are used to select labels in HMTL documents, so how do you do this? The selection rules are divided into two parts, which we will introduce separately
- The selector
Selectors are used to select labels that exist on HMTL pages. Selectors fall into several broad categories, as follows:
Selector type | meaning |
---|---|
Element selector (elementname ) |
Select the corresponding label |
Class selector (.classname ) |
Select the label with the corresponding class name |
ID The selector (#idname ) |
Select with correspondingID The label of the |
Wildcard selector (* ) |
Select all the tags |
Property selector ([Attribute name = value] ) |
Select the label with the corresponding rule attribute |
Pseudo class selector | Selects the label specified by the pseudo class |
Property selectors can be written as follows:
writing | meaning |
---|---|
[attr] |
Selection of beltattr Attribute tag |
[attr=value] |
selectattr Attribute values forvalue The label of the |
[attr~=value] |
selectattr In the attributevalue Labels where words (words not connected to other letters) exist |
[attr|=value] |
selectattr Properties forvalue Or tovalue- Opening label |
[attr^=value] |
selectattr Attribute tovalue Opening label |
[attr$=value] |
selectattr Attribute tovalue Closing tag |
[attr*=value] |
selectattr Properties that containvalue The label of the |
[attr=value I] : [attr=value I] : [attr=value I] : [attr=value I] : [attr=value I] :
Common pseudo classes, as follows
writing | meaning |
---|---|
:active |
Select the TAB that is activated by the user |
:hover |
Select the TAB that is hover over |
:visited |
Select the already visited link |
:focus |
Select the label that gets focus |
:first-child |
Select the first TAB in a set of sibling tags |
:last-child |
Select the last tag in a set of sibling tags |
:first-of-type |
Select the first tag of its type in a set of sibling tags |
:last-of-type |
Select the last tag of its type in a set of sibling tags |
:not(X) |
Not be selectedX All the labels selected by the selector |
:nth-child(an+b) |
a b Is a fixed value,n For any natural number, select the first in a set of sibling labelsan+b An element |
:nth-last-child(an+b) |
Same rule as above, match from back to front |
:nth-of-type(an+b) |
Same rule as above, search from the front to the back, matching the same type of tags |
:nth-last-of-type(an+b) |
Same rule as above, match from back to front |
:only-child |
If the parent tag has only one child element, the child tag is selected |
:only-of-type |
If there is only one child element of this type in the parent tag, the child tag is selected |
- Hyphen (symbol in quotes)
The concatenation dictates how the selectors should be combined, but for the sake of explanation, I’ll give the symbol a name, and the final selection rule will simply be read back to front.
symbol | The name | meaning |
---|---|---|
' ' (not) |
and | Selector stack |
', ' |
or | Selector sharing |
' ' (space) |
Within the | Offspring to choose |
'>' |
In the first level | Subelement selection |
'+' |
The first one after that | Adjacent brother selection |
'~' |
All the rest | Brother to choose |
Give some examples
p.class1
p,div
p .class1
p > .class1
p + .class1
p ~ .class1
Let’s say it:
- The selected
p
And withclass1
The label of the class name. - The selected
p
The label ordiv
The label. - The selected
p
With within the labelclass
The label of the class name. - The selected
p
Label inside the first level carriesclass
The label of the class name. - The selected
p
The first one after the tag carriesclass
The label of the class name. - The selected
p
All tags after the tagclass
The label of the class name.
For complex selection rules, such as the following paragraph in bootstrap:
.btn-group > .btn-group:not(:first-child):not(:last-of-type) > .btn {
border-radius: 0;
}
Copy the code
What does it mean?
Read in order: Select the tags with the bTN-group class name that have the first level of the bTN-group class name and are not the first child and are not the last child of the tag that have the first level of the BTN class name.
The corresponding HTML is as follows:
<span class="btn-group">
<span class="btn">Button 1</span>
<span class="btn-group">
<span class="btn">Button 2</span>
<span class="btn">Button 3</span>
<span class="btn">Button 4</span>
</span>
<span class="btn">Button 5</span>
</span>
Copy the code
The selected label is button 2/3/4.
We understand this rule in the sense that a BTN under a BTN-group within a BTN-group should not have rounded corners (when in the middle). Because normal buttons are rounded, and buttons in the button group as long as the left and right buttons with rounded corners, at this time, you need to use special means to remove the rounded elements to select, and remove rounded corners.
Then we are looking at the content of our translation, is it not so convoluted?
Bootstrap style rules: Bootstrap style rules
.btn-group > .btn-group:last-of-type:not(:first-child) > .btn:first-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
Copy the code
So much for selectors, let’s talk about the CSS properties in the declaration block.
Style categories (attributes)
There are many styles in the CSS. According to the style effect, they can be roughly divided into the following categories
Categories: | role | On behalf of the property |
---|---|---|
The font | Controls the font display | font-* color text-transform text-decoration text-shadow |
typography | Control the typesetting of the text | text-align text-align-last text-indent text-overflow line-height word-spacing letter-spacing |
background | Controls the background display of elements | background-* |
layout | Controls the layout behavior of elements | flex Series of attributesgrid Series of attributes |
Document flow correlation | Controls the position of elements in the document flow | position top left bottom right z-index float clear |
The list of | Control the behavior of lists | list-* |
The box model | Controlling element size | width height padding border margin box-sizing |
Animation & Transition | Control element animation | transition-* transform animation-* @keyframes |
This article introduces what CSS is, not what CSS has, so don’t delve too deeply into the details of these properties. Check out the CSS Reference for more information.
Inheritance of attributes
As we mentioned in the beginning, CSS stands for cascading style sheets, and cascading stands for inheritance of properties.
This inheritance can be summed up simply in one sentence:
The font style and article layout style of the parent tag are inherited by the quilt tag, which means that the child tag owns these attributes without writing them.
Several special values
There are a few special property values in CSS that need special attention:
unset
– If the property is an inherited property, the inherited value is used, otherwise the browser default value is usedinitial
– Use the initialized value, which is the browser defaultinherit
– Use inherited values
The weight
Since the same label can be selected by different selection rules, a situation arises. If multiple selection rules simultaneously select the same element and set the same attribute, which rule defines the attribute for the label to be displayed?
If different CSS rules set the same attribute for the same label, the CSS selection rule with the highest weight overrides the style setting with the lowest weight.
What is the weight, after the above introduction, CSS Settings tag styles are as follows
- Write directly on the tag style property
- The ID selector
- Class name selector
- pseudo-classes
- Label selector
- The wildcard
From top to bottom, the selectors are weighted in decreasing order, just as in the same bill, the 100 bill represents more than the 10 bill, but unlike the bill, the high weight will always take precedence over the low weight selector, no matter how many low weight selectors there are.
To remove the style we use an array to represent the weights of the selection rules.
[0.0.0.0.0]
Copy the code
From left to right: ID selectors, class name selectors, pseudo-classes, label selectors, wildcards, all with initial values of 0. We can change the selection rules to determine the final array, such as the very complicated BTN selection:
.btn-group > .btn-group:not(:first-child):not(:last-of-type) > .btn {
border-radius: 0;
}
Copy the code
From left to right, each selector appears, incrementing the array in the corresponding array by one, so the final array of the previous rule is as follows:
[0.3.2.0.0]
Copy the code
At this point, some friends may ask, pseudo-class selection has 4 ah, how is 2? Note that: :not pseudo-classes are only meant to negate and do not add weight.
So how do the weights compare?
In simple terms, from front to back, who is bigger than who, who has the highest weight. I believe that write a comparison program we will understand:
function compare(weight1, weight2){
for(let i = 0; i < 5; i++){
if(weight1[i] ! == weight2[i]){if(weight1[i] > weight2[i]){
console.log('Participation is important');
}else{
console.log('Two powers matter');
}
return; }}}Copy the code
What about the style weights specified by style?
The weight specified by the style style is higher than the weight specified by the ID selector.
What if we want to change the style specified in the CSS file?
Use! The most important modifier is a specific sample. As shown below.
p {
color: red ! important;
}
Copy the code
The font color of the p tag is red, even if the style is set.
To sum up: weight grade from high to low:! Word-wrap: break-word! Important > style > Select rule. Just like big Brother said east younger brother dare not say west, weight is also absolutely subordinate to the higher level.
So in order to avoid embarrassing situation, please use carefully! Important.
precompiled
Until now, people have found that CSS has the meaning of cascading, but it is written in one dimension, such as a web page with the following document structure:
<article>
<p>This is a text</p>
</article>
Copy the code
We’ll set the style on the article, p tag, which looks something like this:
article {
font-size: 14px;
}
article p {
color: red;
}
Copy the code
Since the style rules are written in line, they appear one-dimensional, and the hierarchy of tags is not reflected in them, it would be nice to write them like this:
article { font-size: 14px; p { color: red; }}Copy the code
From the style of writing to explain the hierarchy, p tag inherited style is clear, but the browser can only recognize one-dimensional style writing, so how to let the browser understand the structure?
Common CSS precompilers are Sass, less, stylus, etc. These precompilers require specific syntax, but all support two-dimensional writing.
So what do these precompilations do?
A simple sentence to convert files that conform to the precompiler syntax into CSS files.
The same syntax for these precompilers is not described here, but there are several websites for you to check:
- sass/scss
- less
- stylus
CSS Modules view
I’m writing this post in 2019, and the reason for this particular timing is because of the emergence of something we need to learn more about: CSS Modules.
What is CSS Modules?
CSS files in which all class names and animation names are scoped locally by default.
Translation:
CSS class names and animation names are all in the same namespace.
Don’t understand? Let me write an example.
The following is pseudo-source code:
// test.css
.box{
color:red;
}
Copy the code
import style from 'test.css'
function Test() {return (<div class={style.box} />)
}
Copy the code
The following is pseudo output:
<div class="_styles__box_34682763478"></div>
Copy the code
_styles__box_34682763478 is the name of the class after the namespace is added, so that the code built does not overwrite the same class name.
In general, one thing CSS Modules does is confuse the class name with the ID and the animation name.
At that point, some developers stepped up and said, oh, this is great, I don’t have to think about class names anymore so they don’t cause conflicts. Calm down and consider these questions:
- It won’t conflict, but what if you want to override the class name?
- Is slow compilation acceptable?
- The style name changes depending on the location of the file or the content of the file. Is this acceptable?
- Whether you need to use a lot of it on the page
JavaScript DOM API
? If so, selection by style name becomes unreliable. - When using the
CSS Modules
Is there a lot of post-project:global
If so, think about it. NoCSS Modules
Is it cheaper?
Here are some scenarios for the problem
You reference a component written by someone else on your team, but you need to modify (override) some styles yourself, and someone else also uses CSS Modules to write styles, so his class name is not fixed, how do you override the style of the tag in this component?
- Notify component writers to change styles? What about generic components?
- Let him set the pattern? The use
CSS Modules
What is the significance of?
Problem # 3: When your application needs to use the DOM API but the style names generated by CSS Modules can change depending on the location or content of the file, the application becomes unreliable. Of course, there is a solution to this problem
js
Also used inCSS Modules
It’s just that debugging becomes a little more difficultjs
The style name used inCSS Modules
To distinguish between,js
和CSS Modules
Use two separate sets of styles
So let’s talk about my experience, or what I think is a good experience
- In the project
CSS Modules
And the originalCSS
Use together. CSS Modules
Only within components, common styles are still used in projects.CSS Modules
Use only for tags that are not structurally related but are not well named, and are not generally used byjs
The selected.CSS Modules
Obfuscation uses namespace generation based on file location, not file content.- Not once a style is common across components
CSS Modules
, through the project specified namespace in the originalCSS
File defined. - The development of
UI
Library or public component, noCSS Modules
.
As a general principle, CSS Modules work with tags that are not common, nameless, or generic across components. These tags can be considered the internal state of a component and cannot be influenced or modified externally.
I don’t know if CSS Modules really solved the problem of slow compilations years later (at least on my computer). CSS Modules are still written in the same way as TRADITIONAL CSS, but with names mixed up and mappings added, but what’s next? I don’t know, but I’ll keep an eye on it.
conclusion
The convention begins with a question and ends with a question
CSS
Where is the cascade of?CSS
What are the two parts of the selection rules, and how do they form each part?- List a list of selectors and separate them into classes?
- What are the common attributes?
- What is a precompiler for?
CSS Modules
What is?- Talk about the
CSS Modules
I think so.
Finally, in fact, this article also wants to talk about layout and document flow content, but the length is too long, also involves HTML, so I plan to separate the layout, there will be a separate page layout, has been recorded, I hope you continue to pay attention to.
reference
- MDN – What is CSS?
- WIKI cascading style sheets
- A brief history of CSS over the past 20 years
- Mdn-css for reference
- The CSS classifies all properties
- Priority and weight of the CSS
The last
All questions are posed by Minimo. Love you