This is bran's second 21 Original article
This article focuses on CSS The core knowledge and common requirements of the project . Although the writing is too long , But it's more basic , Suitable for primary and intermediate front-end reading , When reading, please skip what you have learned .
This article has been written off for a long time , Also referred to many excellent articles , But maybe there is something wrong or bad in the article , Your advice are most welcome , It can be directly mentioned in the comments .
Small tip: The follow-up content is more wonderful .
CSS The core function of is to CSS Property to a specific value . A key value pair of attributes and values is called Statement (declaration).
color: red;
And if you use one or more statements with {}
After wrapping up , That makes up a Declaration block (declaration block).
{ color: red; text-align: center; }
If the declaration block needs to act on the corresponding HTML Elements , That needs to be added Selectors . Selectors and sound blocks make up CSS Rule set (CSS ruleset), Often referred to as CSS The rules .
span { color: red; text-align: center; }
“ The semicolon can be omitted from the last statement in the rule set , But it's not recommended , Because it's easy to make mistakes .
CSS Medium notes :
/* Single-line comments */ /* Multiple lines notes */
stay CSS In file , Except for the notes 、CSS Rule sets and @ The rules Outside , Some other things defined will be ignored by the browser .
CSS Rules are the body of the style sheet , Usually a style sheet includes a large list of rules . But sometimes you also need to include some other information in the style sheet , For example, the character set , Import other external style sheets , Font, etc. , These need special statements to express .
and @ The rules That's the sentence .CSS It contains the following @ The rules :
In addition to the above , The following will be a few more astringent @ The rules To introduce .
@charset[1] Defines the character set used by the style sheet . It must be the first element in the style sheet . If there are more than one @charset
Be declared , Only the first one will be used , And not in HTML Element or HTML Page <style>
Use within elements .
Be careful : Value must be double quoted , And and
@charset "UTF-8";
Usually I don't write the style file @charset The rules , So this one CSS What characters are used to encode the file ?
What character encoding is used in a style sheet file , Browsers have a set of recognition sequences ( Priority from high to low ):
At the beginning of the document Byte order mark[2] Character value , However, the general editor can't see the BOM value ;
HTTP In response to content-type
Field contains charset
Specified value , such as :
Content-Type: text/css; charset=utf-8
CSS Defined in the header @charset The character code specified in the rule ;
<link>
Inside the label charset attribute , This article has been published in HTML5 To abolish ;
The default is UTF-8
.
@import[3] Used to tell CSS The engine introduces an external style sheet .
link and @import Can import a style file , What's the difference between them ?
@supports[4] Used to query specific CSS Whether to take effect , Can combine not、and and or Operator for subsequent operations .
/* If custom properties are supported , Then put body Color set to variable varName Specified colors */ @supports (--foo: green) { body { color: var(--varName); } }
Cascading style sheets , How to understand the cascade here ? Actually, it is. CSS One of the core features of , Algorithm for merging attribute values from multiple sources . For example, for a certain HTML label , There are many CSS When statements can work , So who should work in the end ? It's about that .
Styles for different sources , It will be stacked in the following order , The lower you go, the higher the priority :
To understand cascading needs to be combined with CSS The priority and inheritance of selectors . For example, for the same selector , The declaration defined later will override the previous ; Styles defined by authors take precedence over styles inherited by default .
CSS The selector is undoubtedly one of its cores , We must master the basic selector and some common pseudo classes . Here's a list of common selectors . For more usage of selectors, see MDN CSS Selectors[5].
h1
.checked
#picker
*
Attribute selector
[attr]
: The element that specifies the attribute ;[attr=val]
: An element whose attribute is equal to the specified value ;[attr*=val]
: Attribute contains the element of the specified value ;[attr^=val]
: Attribute begins with the specified value ;[attr$=val]
: Attribute ends with the specified value ;[attr~=val]
: Property contains the specified value ( Complete words ) The elements of ( It is not recommended to use );[attr|=val]
: Property to specify the value ( Complete words ) Elements at the beginning ( It is not recommended to use );A + B
A ~ B
A > B
A B
Conditional pseudo class
:lang()
: Match page elements based on element language ;:dir()
: Elements that match a particular direction of writing ;:has()
: Matches the element that contains the specified element ;:is()
: Matches the elements in the specified selector list ;:not()
: Used to match elements that do not match a set of selectors ;Behavior pseudo class
:active
: Mouse activated elements ;:hover
: Hovering elements of the mouse ;::selection
: The element selected by the mouse ;State pseudo class
:target
: The element of the current anchor ;:link
: Unreached link elements ;:visited
: Visited link elements ;:focus
: Enter the focused form element ;:required
: Enter required form elements ;:valid
: Enter legal form elements ;:invalid
: Enter illegal form element ;:in-range
: Enter form elements within the scope ;:out-of-range
: Enter form elements out of range ;:checked
: Select the selected form element ;:optional
: Options optional form elements ;:enabled
: Event enabled form elements ;:disabled
: Event disabled form elements ;:read-only
: Read only form elements ;:read-write
: Readable and writable form elements ;:blank
: Enter a blank form element ;:current()
: Browsing elements in ;:past()
: Browsed elements ;:future()
: Elements not browsed ;Structure pseudo class
:root
: Root element of the document ;:empty
: Elements without children ;:first-letter
: The initial of the element ;:first-line
: The first line of elements ;:nth-child(n)
: The element that specifies the order index in the element ;:nth-last-child(n)
: The element that specifies the reverse index in the element ;;:first-child
: The first element in the element ;:last-child
: The tail element in the element ;:only-child
: The parent element has only the element of that element ;:nth-of-type(n)
: Label that specifies the order index in the label ;:nth-last-of-type(n)
: Label that specifies the reverse index in the label ;:first-of-type
: The first label in the label ;:last-of-type
: The tag is the tail tag ;:only-of-type
: The parent element has only the label of that label ;::before
: Insert content before the element ;::after
: Insert content after the element ;Priority is assigned to the specified CSS A weight of the statement , It is determined by the value of each selector type in the matched selector . For memory , The weight can be divided into the following levels , The larger the number, the higher the weight :
You can see the inline style ( Through the elements style Property defined styles ) Is higher than any selector ; And add... To the property value !important
You can also raise the priority to the highest level , Because it has the highest priority , So it needs to be used with caution , Here are some tips for use :
stay CSS One of the most important features in is that the child element inherits the calculated value of the corresponding attribute of the parent element . For example, the page root element html The default text color is black , All other elements in the page will inherit this color , After stating the following pattern ,H1 The text will turn orange .
body { color: orange; } h1 { color: inherit; }
imagine , If CSS There's no inheritance in , Then we need to set up labels for different texts color, The result is CSS The size of the file increases infinitely .
CSS Many properties , But not all attributes can inherit the corresponding attributes of the parent element by default , Which attributes are inherited by default ? It must be properties that don't affect the page layout , It can be divided into the following categories :
font-family
、font-style
、font-size
、font-weight
etc. ;text-align
、text-indent
、text-decoration
、text-shadow
、letter-spacing
、word-spacing
、white-space
、line-height
、color
etc. ;list-style
、list-style-image
、list-style-type
、list-style-position
etc. ;visibility
、cursor
etc. ;For other properties that are not inherited by default, you can also control the inheritance behavior through the following property values :
inherit
: Inherit the calculated value of the corresponding attribute of the parent element ;initial
: Apply the default value for this property , such as color The default value of is #000
;unset
: If the property is inheritable by default , Then take inherit
The effect of , Otherwise, the same as initial
;revert
: The effect is equivalent to unset
, Compatibility is poor .stay CSS In the world of , I'll go from left to right 、 From top to bottom in order to display . Under normal circumstances, the page will be divided into line by line display , And each row may consist of multiple columns , So visually, it's from top to bottom, from left to right , And this is CSS Flow layout in , It's also called document flow . Document flow is like water , Can adapt to the container , Generally, it has the following characteristics :
How to break away from the document stream ?
The document flow of shedding refers to the normal document flow of node shedding , Other nodes in the normal document flow will ignore that node and fill its original space . Once the document is out of stream , When calculating the height of its parent node, its height is not included in , The de flow node does not occupy space . There are two ways to get elements out of the document stream : Floating and positioning .
position: absolute;
) Or fixed positioning (position: fixed;
) It also takes elements out of the document stream , And the empty position will be automatically filled by subsequent nodes .stay CSS Any element in a box can be seen as a box , And a box is made up of 4 Part of : Content (content)、 padding (padding)、 Frame (border) And the outer margin (margin).
The box model has 2 Kind of : Standard box model and IE The box model , Ben is made up of W3C and IExplore Set standards .
If you set the following style for an element :
.box { width: 200px; height: 200px; padding: 10px; border: 1px solid #eee; margin: 10px; }
The standard box model holds that : The actual size of the box = Content ( Set the width of / high ) + padding + Frame
therefore .box
The width of the element content is 200px
, And the actual width is width
+ padding-left
+ padding-right
+ border-left-width
+ border-right-width
= 200 + 10 + 10 + 1 + 1 = 222.
IE The box model thinks : The actual size of the box = Set the width of / high = Content + padding + Frame
.box
The actual width occupied by the element is 200px
, And the true width of the content is width
- padding-left
- padding-right
- border-left-width
- border-right-width
= 200 - 10 - 10 - 1 - 1 = 178.
Now, most advanced browsers use the standard box model by default , And like IE6 This is the default usage IE Box model .
stay CSS3 A new attribute has been added to box-sizing
, Allow developers to specify what standards the box uses , It has 2 It's worth :
content-box
: Standard box model ;border-box
:IE The box model ;Visual format model (Visual formatting model) It's a computational rule used to process and display documents on visual media .CSS Everything in the world is a box , The visual formatting model is to specify how these boxes should be placed on the page , This model depends on many factors when calculating , such as : Box size 、 Box type 、 Positioning scheme ( Floating or positioning )、 Sibling elements or sub elements and other factors .
Visual formatting model
As you can see from the figure above, the visual formatting model involves a lot of content , If you are interested in further research, you can see this in combination with the figure above W3C Documents Visual formatting model[6]. So here's a brief introduction to box types .
The type of box is made up of display decision , At the same time, set... To an element display after , It's going to determine the box 2 Two display types (display type):
External display , Box types can be divided into 2 class :block-level box( Block box ) and inline-level box( In line box ).
According to the figure above, you can list which block level and intra line level boxes there are :
All block level boxes will participate in BFC, In a vertical arrangement ; And all the in-house boxes will attend IFC, Show horizontal arrangement .
besides ,block、inline and inline-block What's more specific ?
block
inline
inline-block
On the inside , In fact, the element is regarded as a container , It's wrapped in text or other sub elements .container box According to display The value is different. , It is divided into 4 Kind of :
It is worth mentioning that if img This replacement element (replaced element) Stated as block Will not produce container box Of , Because replacing elements like img The original intention of the design is only through src Replace the content with a picture , I didn't even think about it as a container .
Reference resources :
Format context (Formatting Context) yes CSS2.1 A concept in the specification , It's about a rendered area of the page , It specifies how the sub elements in the rendering area are typeset and interact with each other .
Different types of boxes have different formatting contexts , There's probably this 4 class :
among BFC and IFC stay CSS Plays a very important role in , Because they directly affect the layout of the web page , So we need to have a deep understanding of the principle .
Block formatting context , It's a separate render region , Only block level boxes participate in , It specifies how the internal block level boxes are laid out , And it has nothing to do with the outside of the region .
Figure from yachen168
BFC Rendering rules
How to create BFC?
BFC Application scenarios
1、 Adaptive two column layout
Application principle :BFC The floating area does not overlap with the floating area , So you can fix the width of the sidebar and float it to the left , And trigger on the right side BFC, Make its width adaptive to the remaining width of the line .
<div class="layout"> <div class="aside">aside</div> <div class="main">main</div> </div>
.aside { float: left; width: 100px; } .main { <!-- Trigger BFC --> overflow: auto; }
2、 Clear internal float
The problem with floating is that the parent element collapses high , So the problem that needs to be solved to clear the float is to make the height of the parent element return to normal . While using BFC The principle of clearing floats is : Calculation BFC Altitude time , Floating elements are also involved in the calculation . Just trigger the parent element BFC that will do .
.parent { overflow: hidden; }
3、 Vertical protection margin Merge
BFC One of the principles of rendering : The same BFC Down the vertical margin There will be a merger . So if you let 2 Two elements are not in the same BFC In order to prevent vertical margin Merge . Then how to make 2 Two adjacent sibling elements are not in the same BFC What about China? ? One of the elements can be wrapped with a layer of , And then trigger its envelope BFC, thus 2 Two elements will not be in the same BFC It's in .
<div class="layout"> <div class="a">a</div> <div class="contain-b"> <div class="b">b</div> </div> </div>
.demo3 .a, .demo3 .b { border: 1px solid #999; margin: 10px; } .contain-b { overflow: hidden; }
In view of the above 3 individual Example , You can combine this BFC Application example Better with watching .
Reference resources :CSS principle - Formatting Context[9]
IFC It's very simple , Block level elements contain only inline level elements , The thing to notice is when IFC When block level elements are inserted in , Two anonymous blocks are generated to separate the parent element , Produce two IFC.
IFC Rendering rules
For the above IFC Rendering rules , Can you analyze the following code IFC What's the environment like ?
<p>It can get <strong>very complicated</storng> once you start looking into it.</p>
Corresponding to the above string HTML The analysis is as follows :
Reference resources :Inline formatting contexts[10]
IFC Application scenarios
Steal laziness ,demo I'm not going to do it .
The page displayed on the computer display screen is actually a three-dimensional space , The horizontal direction is X Axis , The vertical direction is Y Axis , And the direction from the screen to the eye can be seen as Z Axis . many HTML The priority of an element depends on its own attributes Z In a certain order on the axis , And that's what the cascading context is about .
-w566
Our first impression of cascading context may come from z-index, I think the bigger it is , The closer to the screen viewer , So the higher the cascade level is , It's true , But the content of cascading contexts is much more than that :
Before you look at the level and order of stacking , Let's first look at how to generate a cascading context , specific HTML Element or CSS Attribute produces a cascading context ,MDN Here's a list of , An element that meets any of the following conditions produces a cascading context :
Cascade level
Cascade level refers to nodes in three-dimensional space Z Up and down on the axis . There are two situations :
The cascading level of a common node is determined by its cascading context , The comparison of cascading levels makes sense only in the current cascading context , Comparison without the current cascading context becomes meaningless .
Cascade order
If there are multiple elements in the same cascading context , So what's the stacking order between them ?
The lower the list, the higher the priority , The visual effect is that the easier it is for users to see ( Not covered by other elements ):
How to compare the stacking levels of two elements ?
Reference resources : Understand thoroughly CSS Cascading context 、 Cascade level 、 Cascade order 、z-index[11]
CSS The declaration of is made up of properties and values , And there are many types of values :
And there are also some values that need units , such as width: 100px, there px It's a unit of length , A unit of length other than px Outside , More commonly used are em、rem、vw/vh etc. . What's the difference between them ? And when should they be used ?
Screen resolution refers to the number of pixels in the horizontal and vertical direction of the screen , Like resolution 1920×1080 It means that the horizontal direction contains 1920 Number of pixels , The vertical direction contains 1080 Number of pixels .
and px It means CSS The pixel , stay CSS It's an absolute unit of length , It's also the most basic unit , Other length units are automatically converted to px. But for devices , It's actually a relative unit of length , For example, the width and height are 2px, On a normal screen , In fact, that is 4 Pixels , And on the device pixel ratio (devicePixelRatio) by 2 Of Retina Under the screen , It has 16 Pixels . So with the same screen size , The higher the screen resolution , The more delicate the display .
Here we are. , There are also some related concepts that need to be sorted out :
Device pixel (Device pixels)
The physical pixels of the device screen , It shows how many pixels there are on the screen ; It's similar to screen resolution .
Device pixel ratio (DPR)
The device pixel ratio represents 1 individual CSS A pixel is equal to a few physical pixels .
Calculation formula :DPR = The number of physical pixels / Logical pixels ;
In the browser, you can use window.devicePixelRatio To get the DPR.
Pixel density (DPI/PPI)
Pixel density is also called display density or screen density , Abbreviation for DPI(Dots Per Inch) perhaps PPI(Pixel Per Inch). From a technical point of view ,PPI It only exists in the field of computer display , and DPI Only in the field of printing or printing .
Calculation formula : Pixel density = The pixel size of the diagonal of the screen / Physical dimensions
such as , For resolution 750 * 1334 Of iPhone 6 Come on , Its pixel density is :
Math.sqrt(750 * 750 + 1334 * 1334) / 4.7 = 326ppi
Device independent pixel (DIP)
DIP Especially for Android It's derived from equipment , The reason is that Android screens are so large , So in order to display as much as possible and device independent , And the concept that we put forward . It is calculated based on the screen density , I think when the screen density is 160 When ,px = DIP.
Calculation formula :dip = px * 160 / dpi
em yes CSS One of the units of relative length in . It's actually relative , So who is it relative to ? It has 2 Layer meaning :
We all know that every browser gives HTML Root element html Set a default font-size, And this value is usually 16px. That's why 1em = 16px The reason for that .
em When calculating, it will be calculated layer by layer , such as :
<div> <p></p> </div>
div { font-size: 2em; } p { font-size: 2em; }
For the above structure HTML, Because of the root element html The font size is 16px, therefore p The final calculated font size of the tag will be 16 * 2 * 2 = 64px
rem(root em) and em equally , It's also a unit of relative length , however rem The opposite is HTML The root element of the html.
rem Because it's based on html Of font-size To calculate , So it's usually used for adaptive websites or H5 in .
Like doing H5 When , The front end usually makes UI to 750px Wide design , And it can be developed based on iPhone X The size of the 375px * 812px To write pages , In this way , You can use the following JS Automatically calculate the root element according to the width of the current page html Benchmark of font-size How much is the .
(function (doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', psdWidth = 750, // Width of design drawing recalc = function () { var clientWidth = docEl.clientWidth; if ( !clientWidth ) return; if ( clientWidth >= 640 ) { docEl.style.fontSize = 200 * ( 640 / psdWidth ) + 'px'; } else { docEl.style.fontSize = 200 * ( clientWidth / psdWidth ) + 'px'; } }; if ( !doc.addEventListener ) return; // When binding events, it is best to cooperate with the anti shake function win.addEventListener( resizeEvt, debounce(recalc, 1000), false ); doc.addEventListener( 'DOMContentLoaded', recalc, false ); function debounce(func, wait) { var timeout; return function () { var context = this; var args = arguments; clearTimeout(timeout) timeout = setTimeout(function(){ func.apply(context, args) }, wait); } } })(document, window);
For example, when the view is 375px When , After calculation html Of font-size Would be 100px, What good is that ? The advantage is that it's easy to write styles , For example, measured from the design drawings header Height is 50px Of , When we write styles, we can directly write :
header { height: 0.5rem; }
Each dimension measured from the design drawing is divided by 100 You can get the... Of the current element rem value , It doesn't have to be calculated , Very convenient . Tell you in secret , If you calculate the above string html label font-size Of JS In code 200 Replace with 2, That's calculating rem It doesn't need to be in addition to 100 了 , How much is measured from the design drawings px, Just write as many rem.
vw and vh Units of length relative to the width and height of the screen view :
stay JS in 100vw = window.innerWidth,100vh = window.innerHeight.
vw/vh The emergence of the new layout makes it possible to write an adaptive layout scheme , Developers are no longer limited to rem 了 .
Units relative to the view , except vw/vh Outside , also vmin and vmax:
CSS There are many kinds of values used to represent colors in , Enough to form a system , So here is a special section to explain it .
according to CSS Color draft [12] The color value type mentioned in , They can be divided into these categories :
Color keywords (color keywords) Is a case insensitive identifier , It represents a specific color , such as white( white ), black (black) etc. ;
The list of acceptable keywords is in CSS Changes have taken place in the course of the evolution of :
Here's a picture of 16 A basic color , Also called VGA Color . So far CSS There are a total of color keywords 146 individual , Here you can see Complete color keyword list [13].
VGA Color
It should be noted that if the color keyword is wrong when declaring , The browser will ignore it .
transparent The keyword represents a completely transparent color , That is, the color will look like the background color . Technically speaking , It's with alpha The channel is the minimum black , yes rgba(0,0,0,0) Abbreviation .
What are the application scenarios of transparent keywords ?
Implementation triangle
Here's a picture with 4 A square filled with borders , If you understand it, you will probably know how to use it CSS I wrote triangles .
div { border-top-color: #ffc107; border-right-color: #00bcd4; border-bottom-color: #e26b6b; border-left-color: #cc7cda; border-width: 50px; border-style: solid; }
use transparent The principle of realizing triangles :
Look at the example :
Increase the click area
The area of the button that is often clicked on the mobile terminal is very small , But because the reality is not so good, make it bigger , So a common method is to increase the click area of the button through the transparent border :
.btn { border: 5px solid transparent; }
currentColor It will take the text color value of the parent element inherited from the current element or the declared text color value , namely computed After color value .
such as , For the following CSS, The border color of the element will be red:
.btn { color: red; border: 1px solid currentColor; }
RGB[A] Color is made by R(red)-G(green)-B(blue)-A(alpha) The color space composed of .
stay CSS in , It has two representations :
Hexadecimal symbols
RGB The value range for each color in is 00~ff, The higher the value, the darker the color . So a normal color is 6 Six hexadecimal characters plus # form , For example, red is #ff0000.
If RGB Colors need to be opaque , Then you need to add alpha The value of the channel , Its scope is also 00~ff, For example, one with opacity is 67% You can write in red like this #ff0000aa.
When using hexadecimal symbols to represent colors , It's all used 2 A hexadecimal represents a color , If this 2 Two characters are the same , It can also be reduced to write only 1 individual , such as , Red #f00; belt 67% Red opacity #f00a.
Function sign
When RGB When expressed as a function , The range of each value is 0~255 perhaps 0%~100%, So red is rgb(255, 0, 0), perhaps rgb(100%, 0, 0).
If you need to use a function to represent the color value with opacity , The range of values is 0~1 And the decimals between them or 0%~100%, Take... For example 67% The red color of opacity is rgba(255, 0, 0, 0.67) perhaps rgba(100%, 0%, 0%, 67%)
“ It should be noted that RGB this 3 Color values need to be written in a consistent way , Either use numbers or percentages , And the value of opacity can not be equal to RGB Keep it in line . such as rgb(100%, 0, 0) This writing is invalid ; and rgb(100%, 0%, 0%, 0.67) It works .
In the 4 generation CSS In the color standard , A new function writing method has been added , That is to say RGB Change the median comma to a space , But the RGB and alpha Change the comma in to /, Take... For example 67% The red opacity can be written like this rgba(255 0 0 / 0.67). In addition, I put rgba It's a combination of rgb In the function , namely rgb You can directly write colors with opacity .
HSL[A] Color is made up of hues (hue)- saturation (saturation)- brightness (lightness)- The color system of opacity .
The writing method can be referred to RGB Writing , It's just that the values of the parameters are different .
Set the opacity of a button to 67% The red ones color Writing , All of the following are the same :
button { color: #ff0000aa; color: #f00a; color: rgba(255, 0, 0, 0.67); color: rgb(100% 0% 0% / 67%); color: hsla(0, 100%, 50%, 67%); color: hsl(0deg 100% 50% / 67%); }
tip : stay Chrome DevTools You can press and hold shift + The left mouse button can switch the color representation .
Media query is a pointer to different devices 、 Specific device features or parameters can be customized to modify the style of the website .
You can give <link>
add media Property to specify which devices the style file can only work on , If not specified, the default is all, It works for all devices :
<link rel="stylesheet" src="styles.css" media="screen" /> <link rel="stylesheet" src="styles.css" media="print" />
Which device types are supported ?
“ It should be noted that : adopt media designated Although the resource does not match its device type , But the browser still loads it .
In addition to <link>
Let the specified device take effect , You can also use @media
Give Way CSS Rules can only take effect under certain conditions . Responsive pages use @media So that a page can be adapted at the same time PC、Pad And mobile phones .
@media (min-width: 1000px) {}
Media queries support logical operators :
Media query also supports Lots of media features [14], So that it can write very complex query conditions :
/* The minimum height of user equipment is 680px Or vertical mode screen device */ @media (min-height: 680px), screen and (orientation: portrait) {}
Before, we used to use variables in the preprocessor , And now CSS Variable usage is also supported in . By customizing the property, you can refer to it where you want to use it .
Custom attributes are cascading like normal attributes , The statement is in :root When I go down , Available in full text , If you declare a custom attribute under an element , It can only be used under it and its sub elements .
The custom attribute must pass --x
Format statement for , such as :--theme-color: red; When using custom properties , Need to use var function . such as :
<!-- Define custom properties --> :root { --theme-color: red; } <!-- Using variables --> h1 { color: var(--theme-color); }
This is using CSS Custom attribute matching JS Realize the dynamic adjustment of the elements of box-shadow, You can see this codepen demo.
Retina The screen has a higher resolution than the ordinary screen , So on the mobile end 1px The border will look thicker , For the sake of beauty, we usually need to refine this line . Here's an article listing 7 We can refer to :7 One way to solve the mobile end Retina The screen 1px Border problem [15]
And here's the last one through pseudo classes and transform A relatively perfect solution :
Just set a single bottom border :
.scale-1px-bottom { position: relative; border:none; } .scale-1px-bottom::after { content: ''; position: absolute; left: 0; bottom: 0; background: #000; width: 100%; height: 1px; -webkit-transform: scaleY(0.5); transform: scaleY(0.5); -webkit-transform-origin: 0 0; transform-origin: 0 0; }
Simultaneous setting 4 Borders :
.scale-1px { position: relative; margin-bottom: 20px; border:none; } .scale-1px::after { content: ''; position: absolute; top: 0; left: 0; border: 1px solid #000; -webkit-box-sizing: border-box; box-sizing: border-box; width: 200%; height: 200%; -webkit-transform: scale(0.5); transform: scale(0.5); -webkit-transform-origin: left top; transform-origin: left top; }
What is floating : Floating elements break away from the document flow and to the left / Floating to the right , Until the parent element or another floating element is encountered .
Why clear floating , What problems does it cause ?
Because floating elements will break away from the normal document flow , It doesn't occupy the position of the document stream , So if there are floating elements under a parent element , Then the parent element cannot be supported by the floating element , In this way, the parent element loses its height , This is the so-called floating caused by the collapse of the parent element height problem .
Once the height of the parent element collapses, the layout of the following elements will be affected , To solve this problem , So you need to clear the float , Restore the height of the parent element , So how to do it ?
Here are two approaches : adopt BFC To get rid of 、 adopt clear To get rid of .
Described above BFC When I mentioned it , Calculation BFC The height of the floating sub element is also included in the calculation , With this rule, you can float clearly .
Suppose a parent element parent Internal only 2 Sub elements child, And they're all left floating , This is the time parent If the height is not set , Because the float caused the height to collapse , therefore parent It's going to be 0, At this point, just give parent To create a BFC, Then its height can be restored .
And produce BFC There are many ways , We can set... For the parent element overflow: auto To simply implement BFC Remove the floating , But for compatibility IE It is best to overflow: hidden.
.parent { overflow: hidden; }
adopt overflow: hidden To clear the float is not perfect , Elements are truncated when they have shadows or drop-down menus , So this method is limited .
I'll post the conclusion first :
.clearfix { zoom: 1; } .clearfix::after { content: ""; display: block; clear: both; }
The core principle of this writing is through ::after Pseudo element is to generate a block level element with empty content after the last child element of the parent element , And then through clear Move this pseudo element behind all the floating elements before it , Draw a picture to understand .
You can combine this codepen demo Let's understand the picture above clear Understand the floating principle .
Above this demo Or the content of the pseudo element is set to ::after, The actual use needs to be set to an empty string , Let it have a height of 0, Thus, the height of the parent element is supported by the actual child element .
It's basically a solution that everybody is using now to clear floats , Very versatile .
Reference resources :CSS Float and clear float in , Sort out [16]
For the same type of HTML label , Different browsers often have different performance , So when the website is made , Developers usually need to clear the default styles of these browsers , Make web pages consistent in different browsers .
For clearing browser default styles , Long ago CSS The master Eric A. Meyer Just did it . It's just writing a bunch of common styles to reset the browser's default styles , These styles are usually put in a place called reset.css In file . Like the master's reset.css[17] It's written like this :
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; }
This one of his reset.css It's said to be the most widely used scheme to reset styles .
except reset.css Outside , And then it came Normalize.css[18] . About Normalize.css, Its author necolas I wrote an article about it , And talked about it and reset.css The difference between . This is a translation of the article he wrote : Let's talk about Normalize.css[19].
The article introduces :Normalize.css It's just a very small CSS file , But it's default HTML Element styles provide a high degree of consistency across browsers . Compared to traditional CSS reset,Normalize.css It's a kind of modern 、 by HTML5 A good alternative to prepare , Now there are many well-known frameworks and websites using it .
Normalize.css You can see the specific style here Normalize.css
The difference in reset.css,Normalize.css It has the following characteristics :
Default : The character is too long and overflows the container
The part beyond the character is wrapped
Use hyphens when characters are out of position
A single line of text exceeds the ellipsis
Multiline text beyond ellipsis
Take a look at examples of these scenarios : codepen demo
What's interesting is that I saw it just two days ago chokcoco I also wrote an article about text overflow , The main highlight is the whole block of text overflow processing . What is a whole text ? such as , The following technical tag belongs to the whole text :
Besides, he's also interested in iOS/Safari Compatible processing , If you are interested, you can read it :CSS The whole text overflow ellipsis characteristic research [20].
Let the element take on the shape of horizontal and vertical center in the parent element , Nothing but 2 In this case :
With all the horizontal and vertical centering schemes listed below, here's a codepen demo, It's better to read with examples .
Horizontal center
Such elements need to be horizontally centered , Then the parent element must be a block level element (block level
), And the style needs to be set on the parent element :
.parent { text-align: center; }
Vertical center
Method 1 : By setting the space between the top and bottom to achieve the effect of vertical center :
.single-line { padding-top: 10px; padding-bottom: 10px; }
Method 2 : By setting height
and line-height
The consistency reaches the vertical center :
.single-line { height: 100px; line-height: 100px; }
Method 1 :absolute + negative margin
Method 2 :absolute + margin auto
Method 3 :absolute + calc
Here's a list of 6 Methods , Referring to Yan Haijing Articles written , Two of them line-height and writing-mode After looking at the plan, I exclaimed : There is also this operation ? I learned. I learned .
Method 1 :absolute + transform
Method 2 :line-height + vertical-align
Method 3 :writing-mode
Method four :table-cell
Method five :flex
Methods six :grid
Several examples are written for the following scenarios : codepen demo
Method 1 :float + overflow(BFC principle )
Method 2 :float + margin
Method 3 :flex
Method four :grid
Several examples are written for the following scenarios : codepen demo
Method 1 : The holy grail layout
Method 2 : Double wing layout
Method 3 :float + overflow(BFC principle )
Method four :flex
Method five :grid
It's better to read with examples :codepen demo
Method 1 :padding + negative margin
Method 2 : Set the parent background picture
Listed 4 Methods , It's all based on the following HTML and CSS Of , Reading with examples is better :codepen demo
<div class="layout"> <header></header> <main> <div class="inner"></div> </main> <footer></footer> </div>
html, body, .layout { height: 100%; } body { margin: 0; } header, footer { height: 50px; } main { overflow-y: auto; }
Method 1 :calc
Method 2 :absolute
Method 3 :flex
Method four :grid
This is my continuation 2 The article that Zhou finished , It's my own right to CSS A summary of , Although it's very long , But not enough to cover all CSS Knowledge , Like animation and some CSS3 The new features of are not involved at all , It's estimated that it will take tens of thousands of words to write down ( It's just laziness ? ).
It's not easy to draw code words , If you like it or if it helps you in the least , To point a ? Ha , Praise is my motivation . At the same time, I hope I can insist on writing down seriously , Because in the summary to improve their own at the same time, if it can also help more front-end er, That will make me feel very happy .
[1]
@charset: https://developer.mozilla.org/zh-CN/docs/Web/CSS/@charset
[2]
Byte order mark: https://en.wikipedia.org/wiki/Byte_order_mark
[3]
@import: https://developer.mozilla.org/zh-CN/docs/Web/CSS/@import
[4]
@supports: https://developer.mozilla.org/zh-CN/docs/Web/CSS/@supports
[5]
MDN CSS Selectors: https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Selectors
[6]
Visual formatting model: https://www.w3.org/TR/CSS2/visuren.html
[7]
CSS principle - What you don't know display: https://yachen168.github.io/article/display.html
[8]
Format context : https://ithelp.ithome.com.tw/articles/10223896?sc=pt
[9]
CSS principle - Formatting Context: https://yachen168.github.io/article/Formatting-context.html
[10]
Inline formatting contexts: https://www.w3.org/TR/CSS2/visuren.html#inline-formatting
[11]
Understand thoroughly CSS Cascading context 、 Cascade level 、 Cascade order 、z-index: https://juejin.cn/post/6844903667175260174
[12]
CSS Color draft : https://drafts.csswg.org/css-color-3/
[13]
Complete color keyword list : https://codepen.io/bulandent/pen/gOLovwL
[14]
Lots of media features : https://developer.mozilla.org/zh-CN/docs/Web/Guide/CSS/Media_queries#%E5%AA%92%E4%BD%93%E7%89%B9%E6%80%A7
[15]
7 One way to solve the mobile end Retina The screen 1px Border problem : https://www.jianshu.com/p/7e63f5a32636
[16]
CSS Float and clear float in , Sort out : https://www.jianshu.com/p/09bd5873bed4
[17]
reset.css: https://meyerweb.com/eric/tools/css/reset/
[18]
Normalize.css: https://github.com/necolas/normalize.css
[19]
Let's talk about Normalize.css: https://jerryzou.com/posts/aboutNormalizeCss/
[20]
CSS The whole text overflow ellipsis characteristic research : https://juejin.cn/post/6938583040469762055
This article is from WeChat official account. - The sea, here I come (bubuzouweb)
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .
Original publication time : 2021-03-19
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .