In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "summary of the core knowledge points of CSS". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the summary of the core knowledge points of CSS".
Core concepts and knowledge point grammar
The core function of CSS is to set the CSS property to a specific value. A key-value pair of attributes and values is called a declaration.
Color: red
If you wrap one or more declarations in {}, it forms a declaration block.
{color: red; text-align: center;}
Span {color: red; text-align: center;}
"the last declaration in the rule set can omit the semicolon, but it is not recommended because it is error-prone.
Comments in CSS:
/ * single-line comments * / * multiple-line comments * /
In the CSS file, except for comments, CSS rule sets, and @ rules, something else defined will be ignored by the browser.
@ rules
CSS rules are the body of a stylesheet, which usually contains a large list of rules. But sometimes you also need to include other information in the stylesheet, such as character sets, importing other external stylesheets, fonts, etc., which require special statements.
And the @ rule is such a statement. The following @ rules are included in CSS:
Namespace tells the CSS engine that XML namespaces must be considered.
@ media. If the conditions for media query are met, the rules in the conditional rule group will take effect.
@ page, which describes the change in layout when printing a document.
@ font-face, describing the external font that will be downloaded.
@ keyframes, describing the keyframes of the CSS animation.
@ document, the rules in the conditional rule group take effect if the document stylesheet meets the given conditions. (deferred to CSS Level 4 specification)
In addition to the above, some of the more obscure @ rules will be introduced below.
@ charset
@ charset [1] is used to define the character set used by the stylesheet. It must be the first element in the style sheet. If more than one @ charset is declared, only the first one will be used and cannot be used within the HTML element or within the HTML page element.
Note: the value must be wrapped in double quotation marks, and
@ charset "UTF-8"
Usually write style files do not write @ charset rules, so what character encoding is used in this CSS file?
What character encoding is used in a stylesheet file? the browser has a set of recognition order (priority from high to low):
The Byte order mark [2] character value at the beginning of the file, but the BOM value in the header cannot be seen by the general editor.
The content-type field in the HTTP response header contains the value specified by charset, such as:
Content-Type: text/css; charset=utf-8
The character encoding specified in the @ charset rule defined in the CSS file header
The charset attribute in the tag, which has been repealed in HTML5
The default is UTF-8.
@ import
Import [3] is used to tell the CSS engine to introduce an external style sheet.
Both link and @ import can import a style file. What's the difference between them?
Link is a HTML tag, which can import not only CSS, but also other resources, such as pictures, scripts and fonts, while @ import is the syntax of CSS and can only be used to import CSS.
The styles imported by link will be loaded at the same time when the page is loaded, and the styles imported by @ import will not be loaded until the page is loaded.
There is no compatibility problem with link. @ import is not compatible below ie5.
Link can dynamically introduce stylesheets to change styles through the JS operation DOM, while @ import cannot.
@ supports
@ supports [4] is used to query whether a particular CSS is in effect, and subsequent operations can be performed in combination with the not, and, and or operators.
/ * if custom attributes are supported, set the body color to the color specified by the variable varName * / @ supports (--foo: green) {body {color: var (--varName);}} cascading
Cascading stylesheets, how to understand cascading here? In fact, it is one of the core features in CSS, an algorithm for merging attribute values from multiple sources. For example, when there are a lot of CSS statements that can work for a HTML tag, who should work in the end? That's probably what cascading is about.
For styles of different sources, they will be cascaded in the following order, and the lower the priority, the higher the priority:
The declaration in the user agent style sheet (for example, the default style for the browser, used when no other style is set).
A general declaration in a user style sheet (a custom style set by the user. Since Chrome abandoned the functionality of user stylesheets a long time ago, its sorting will no longer be considered here.) .
General declarations in the author's stylesheet (these are the styles set by our Web developers).
The! important declaration in the author stylesheet.
The! important declaration in the user stylesheet.
Cascading needs to be understood in terms of the priority and inheritance of the CSS selector. For example, for the same selector, the declaration defined after it overrides the previous one; the style defined by the author takes precedence over the style inherited by default.
Selector
CSS selector is undoubtedly one of its core, for the basic selector and some common pseudo-classes must be mastered. The commonly used selectors are listed below. For more use of selectors, see MDN CSS Selectors [5].
Base selector
Tag selector: H2
Class selector: .checked
ID selector: # picker
Wildcard selector: *
Attribute selector
[attr]: the element that specifies the attribute
[attr=val]: an element whose attribute is equal to the specified value
[attr*=val]: the attribute contains the element of the specified value
[attr^ = val]: an element whose attribute begins with the specified value
[attr$=val]: an element whose attribute ends with a specified value
[attr~=val]: an element whose attribute contains the specified value (full word) (not recommended)
[attr | = val]: an element whose attribute begins with the specified value (full word) (not recommended)
Combination selector
Neighboring brother selector: a + B
Ordinary brother selector: a ~ B
Sub-selector: a > B
Descendant selector: a B
Pseudo class
Conditional pseudo class
: lang (): matches page elements based on element language
: dir (): an element that matches a specific 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 element
: hover: the element of mouse suspension
:: selection: elements selected by the mouse
State pseudo class
: target: the element of the current anchor
: link: unvisited link element
: visited: visited link element
: focus: enter focused form elements
: required: enter the required form elements
: valid: enter legal form elements
: invalid: enter illegal form elements
: in-range: form elements within the input range
: out-of-range: form elements outside the input range
: checked: form element selected by option
: optional: optional form elements
: enabled: event-enabled form element
: disabled: form element disabled by event
: read-only: read-only form elements
: read-write: readable and writable form elements
: blank: enter an empty form element
: current (): elements in browsing
: past (): browsed element
: future (): unbrowsed element
Structural pseudo class
: root: the root element of the document
: empty: an element without child elements
: first-letter: the initials of the element
: first-line: first line of the element
: nth-child (n): the element of the specified sequential 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 trailing element in the element
: only-child: the parent element has only the element of that element
: nth-of-type (n): the tag in the tag that specifies the sequential index
: nth-last-of-type (n): the tag in the tag that specifies the reverse index
: first-of-type: the tag headed by the tag
: last-of-type: the tail tag in the tag
: only-of-type: the parent element has only the tag of this tag
Pseudo element
:: before: insert content before the element
:: after: insert content after the element
Priority
Priority is a weight assigned to a specified CSS declaration, which is determined by the numerical value of each selector type in the matching selector. In order to remember, you can divide the weights into the following levels, and the higher the value, the higher the weight:
10000:!important
01000: inline styl
00100:ID selector
00010: class selector, pseudo-class selector, attribute selector
00001: element selector, pseudo element selector
00000: wildcard selector, descendant selector, brother selector
You can see that inline styles (styles defined by the style attribute in the element) take precedence over any selector; adding! important to the attribute value gives it the highest priority, because it has the highest priority, so you need to use it carefully. Here are some considerations:
Be sure to give priority to using style rules to solve problems rather than! important
Use important only on specific pages that need to cover the entire site or external CSS
Never use it in your plugin! important
Never use in site-wide CSS code! important
Inheritance
An important feature in CSS is that the child element inherits the calculated value of the corresponding attribute of the parent element. For example, the text color of the page root element html is black by default, and all other elements in the page will inherit this color. When the following style is declared, the H1 text will turn orange.
Body {color: orange;} h2 {color: inherit;}
Imagine that if there is no inheritance in CSS, then we need to set color for different text tags, and as a result, the file size of CSS will increase infinitely.
There are many CSS attributes, but not all of them inherit the corresponding attributes of the parent element by default, so which attributes have the behavior of default inheritance? It must be those properties that do not affect the layout of the page, which can be divided into the following categories:
Font related: font-family, font-style, font-size, font-weight, etc.
Text relevance: text-align, text-indent, text-decoration, text-shadow, letter-spacing, word-spacing, white-space, line-height, color, etc.
List related: list-style, list-style-image, list-style-type, list-style-position, etc.
Other attributes: 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: inherits the calculated value of the attribute corresponding to the parent element
Initial: apply the default value of this attribute, for example, the default value of color is # 000
Unset: if the attribute is inheritable by default, take the effect of inherit, otherwise it is the same as initial
Revert: the effect is equivalent to that of unset, and the compatibility is poor.
Document stream
In the world of CSS, content is displayed in order from left to right and top to bottom. Under normal circumstances, the page will be divided into a line of display, and each row may be composed of multiple columns, so visually it looks from top to bottom from left to right, and this is the streaming layout in CSS, also known as document flow. A document stream, like water, can adapt to the container in which it resides. Generally, it has the following characteristics:
Block-level elements occupy the entire row by default, so multiple block-level boxes are arranged from top to bottom
By default, inline elements are arranged column by column in a row. When a row cannot fit, it will automatically switch to the next row and continue to be arranged according to the column.
How to break away from the document stream?
A decoupled document stream means that after a node offflows a normal document stream, other nodes in the normal document stream will ignore the node and fill its original space. Once a document is out of stream, its height is not taken into account when calculating the height of its parent node, and the de-streaming node does not take up space. There are two ways to detach elements from the document stream: floating and positioning.
Using float moves the element out of the document stream to the left / right boundary of the container or next to another floating element. The space occupied by the floating element will be filled by other elements, and the area occupied after floating will not overlap with other elements.
Using absolute positioning (position: absolute;) or fixed positioning (position: fixed;) also takes the element out of the document stream, and the empty position is automatically filled by subsequent nodes.
Box model
In CSS, any element can be thought of as a box, and a box is made up of four parts: content (content), inner margin (padding), border (border), and outer margin (margin).
There are two kinds of box models: standard box model and IE box model, which are standards formulated by W3C and IExplore.
If you set the following style for an element:
.box {width: 200px; height: 200px; padding: 10px; border: 1px solid # eee; margin: 10px;}
According to the standard box model, the actual size of the box = content (width / height set) + inner margin + border
So the width of the content of the .box element is 200px, while the actual width is width + padding-left + padding-right + border-left-width + border-right-width = 200 + 10 + 10 + 1 + 1 = 222.
According to the IE box model, the actual size of the box = set width / height = content + inner margin + border
The actual width occupied by the .box element is 200px, while the real width of the content is width-padding-left-padding-right-border-left-width-border-right-width = 200-10-10-1-1 = 178.
Today's high-end browsers basically use the standard box model by default, while antiques like IE6 use the IE box model by default.
A new property, box-sizing, has been added to CSS3, which allows developers to specify what standard the box uses. It has two values:
Content-box: standard box model
Border-box:IE box model
Visual formatting model
The Visual format Model (Visual formatting model) is a computational rule used to process and display documents on visual media. Everything in CSS is a box, while the visual formatting model simply defines 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
From the above picture, we can see that the visual formatting model involves a lot of content, interested in in-depth study can be combined with the above figure to see the W3C document Visual formatting model [6]. So here is a brief introduction to the type of box.
The box type is determined by display, and when you set display to an element, it will determine the two display types of the box (display type):
Outer display type (external display): determines how the element itself is laid out, that is, what formatting context it participates in
Inner display type (internal display): it is tantamount to treating this element as a container, specifying how its internal child elements are laid out and what kind of formatting context they participate in.
Outer display type
In terms of external display, box types can be divided into two categories: block-level box (block level box) and inline-level box (inline level box).
According to the figure above, you can list which block-level and inline-level boxes are available:
Block box: display is block, list-item, table, flex, grid, flow-root, etc.
In-line box: display is inline, inline-block, inline-table, etc.
All block-level boxes participate in BFC and are arranged vertically, while all inline-level boxes participate in IFC and are arranged horizontally.
Besides, what is the more specific difference between block, inline, and inline-block?
Block
Occupies a full row and inherits the width of the parent element by default; multiple block elements will be arranged from top to bottom
Setting width/height will take effect
Setting padding and margin will take effect
Inline
It will not occupy a full line, and the width will vary with the content; multiple inline elements will be displayed in a row from left to right, and if the line does not fit, the line will be wrapped automatically
Setting width/height will not take effect
Setting padding and margin in the vertical direction will not take effect
Inline-block
It is an inline block element, which does not occupy a single line, but can be seen as a block element that can be arranged left and right in a row.
Setting width/height will take effect
Setting padding and margin will take effect
Inner display type
Internally, you actually treat the element as a container, wrapped in text or other child elements. The types of container box can be divided into four types according to the value of display:
Block container: create BFC or IFC
Flex container: building FFC
Grid container: building GFC
Ruby container: not much contact, no introduction.
It is worth mentioning that if the replacement element (replaced element) such as img is declared as block, it will not produce container box, because replacement elements such as img are designed to replace content with images only through src, without thinking about using it as a container.
Reference:
CSS principle-display you don't know [7]
Formatting context [8]
Formatting context
Formatting context (Formatting Context) is a concept in the CSS2.1 specification, which roughly refers to a rendering area in a page that defines how child elements within the rendering area are typeset and interact with each other.
Different types of boxes have different formatting contexts, and there are probably four categories:
BFC (Block Formatting Context) block-level formatting context
IFC (Inline Formatting Context) inline formatting context
FFC (Flex Formatting Context) flexible formatting context
GFC (Grid Formatting Context) grid formatting context
Among them, BFC and IFC play a very important role in CSS, because they directly affect the layout of web pages, so we need to understand their principles deeply.
BFC
The block formatting context, which is a separate rendering area with only block-level boxes involved, specifies how the internal block-level boxes are laid out and has nothing to do with the outside of the area.
The picture is from yachen168.
BFC rendering Rul
The inner boxes will be placed one after another in the vertical direction.
The vertical distance of the box is determined by the margin, and the margin of two adjacent boxes belonging to the same BFC will overlap.
The left side of the margin of each element is in contact with the left side containing the block border (for left-to-right formatting, otherwise vice versa), even if there is a float
The area of the BFC does not overlap with the float box
BFC is an isolated container on the page, and the child elements inside the container do not affect the outer elements. And vice versa.
Floating elements also participate in the calculation when calculating the height of the BFC.
How do I create a BFC?
Root element: html
Non-overflow visible element: overflow is not visible
Set float: the float property is not none
Set location: position is absolute or fixed
Non-block-level elements defined as block-level: display: inline-block/table-cell/table-caption/flex/inline-flex/grid/inline-grid
BFC application scenario
1. Adaptive two-column layout
How it works: the area of the BFC does not overlap with the floating area, so the sidebar can be fixed and floating on the left, while BFC can be triggered for the right content to make its width adaptive to the rest of the line.
Aside
Main
.aside {float: left; width: 100px;} .main {overflow: auto;}
2. Clear the internal float
The problem caused by floats is that the parent element is highly collapsed, so the problem to clear the float is to get the height of the parent element back to normal. The principle of clearing floats with BFC is that when calculating the height of BFC, floating elements are also involved in the calculation. Just trigger the BFC of the parent element.
.parent {overflow: hidden;}
3. Prevent vertical margin merging
One of the principles of BFC rendering: vertical margin under the same BFC will be merged. So vertical margin merging can be prevented if two elements are not in the same BFC. So how do you make two adjacent sibling elements not in the same BFC? You can wrap one of the elements with a layer, and then trigger the BFC of its wrap layer, so that the two elements are not in the same BFC.
A b .demo3 .a, .demo3 .b {border: 1px solid # 999; margin: 10px;} .contain-b {overflow: hidden;}
For the above three examples, it is better to combine this BFC application example with viewing.
Reference: CSS principle-Formatting Context [9]
IFC
The condition for the formation of IFC is very simple. Block-level elements only contain inline-level elements. It should be noted that when block-level elements are inserted in IFC, two anonymous blocks will be generated to separate the parent element, resulting in two IFC.
IFC rendering Rul
The child elements are arranged one after another horizontally, and vertically, starting at the top of the container.
The node cannot declare width and height, where margin and padding are valid horizontally but not vertically
Nodes are aligned in different forms vertically
A rectangular area that contains all the boxes on a row is called the line box of the row. The width of the wire box is determined by the containing block (containing box) and the float in it.
Line box in IFC generally snaps to its containing blocks on the left and right sides, but float elements take precedence.
The line box height in IFC is determined by line-height calculation rules, and multiple line box heights under the same IFC may be different.
When the total width of inline boxes is less than the line box that contains them, their horizontal rendering rules are determined by the value of the text-align attribute.
When an inline box exceeds the width of the parent element, it is divided into multiple boxes, which are distributed across multiple line box. If the child element is not set to force line wrapping, the inline box will not be divisible and will overflow the parent element.
For the above IFC rendering rules, can you analyze what the IFC environment of the following code looks like?
It can get very complicated once you start looking into it.
The analysis of the above string of HTML is as follows:
The p tag is a block container and an IFC will be generated internally
Since a row cannot be displayed completely, two line box are generated; the width of the wire box inherits the width of p; the height is determined by the line-height of the inline box inside
It can get: anonymous inline box
Inline boxes generated by very complicated:strong tags
Once you start: anonymous inline box
Looking into it.: anonymous inline box.
Reference: Inline formatting contexts [10]
IFC application scenario
Horizontal Center: when a block is to be centered horizontally in the environment, setting it to inline-block produces IFC on the outer layer, and it can be centered horizontally with text-align.
Vertical center: create an IFC, stretch the height of the parent element with one of the elements, and then set its vertical-align: middle, while other inline elements can be centered vertically under this parent element.
If I'm lazy, I won't do demo and Tu.
Cascading context
The page displayed on the computer display screen is actually a three-dimensional space, the horizontal direction is the X axis, the vertical direction is the Y axis, and the direction from the screen to the eye can be regarded as the Z axis. The HTML elements are arranged in a certain order on the Z axis according to the priority of the attributes they define, which is what the cascading context describes.
-w566
Our first impression of the cascading context may come from z-index, thinking that the higher the value, the closer to the screen viewer, the higher the cascading level, which is true, but the content of the cascading context is much more than that:
Z-index can stack the order of elements in a cascading context, and its function is that it must be positioned together.
In addition to z-index, the order in which an element is displayed on the Z axis is also affected by the cascading level and cascading order
Before looking at the cascading level and cascading order, let's take a look at how to generate a cascading context. A specific HTML element or CSS attribute generates a cascading context. There is a list in MDN that produces a cascading context for elements that meet any of the following conditions:
Html document root element
Elements that declare position: absolute/relative and whose z-index value is not auto
Declare the element of position: fixed/sticky
A child element of the flex container, and the z-index value is not auto
A child element of the grid container, and the z-index value is not auto
Elements whose opacity attribute value is less than 1
Elements whose mix-blend-mode attribute value is not normal
Elements whose values of any of the following attributes are not none:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Transform
Filter
Perspective
Clip-path
Mask / mask-image / mask-border
Elements with the value of the isolation attribute isolate
Elements with the value of the webkit-overflow-scrolling attribute touch
The will-change value sets any attribute that creates a cascading context element at the non-initial value
The contain attribute value is layout, paint, or an element that contains the combined values of one of them (for example, contain: strict, contain: content).
Cascading grade
Cascading level refers to the up and down order of nodes on the Z axis in three-dimensional space. It is divided into two situations:
In the same cascading context, it describes the upper and lower order of the cascading context elements in the cascading context on the Z axis
Among other ordinary elements, it describes and defines the order of these ordinary elements up and down the Z axis.
The cascading level of an ordinary node is determined by its cascading context. The comparison of cascading levels is meaningful only in the current cascading context, and the comparison without the current cascading context becomes meaningless.
Cascading order
If there are multiple elements in the same cascading context, what is the cascading order between them?
The lower the list, the higher the priority, the easier the visual effect is to be seen by the user (not overridden by other elements):
Border and background in cascading context
Z-index
< 0 的子节点 标准流内块级非定位的子节点 浮动非定位的子节点 标准流内行内非定位的子节点 z-index: auto/0 的子节点 z-index >Child nodes of 0
How do I compare the cascading levels of two elements?
To compare two elements in the same cascading context is to compare them in the cascading order described in the figure above.
If you are not in the same cascading context, you need to compare the level of the cascading context in which the two elements are located.
If both elements are in the same cascading context and the cascading order is the same, the later the cascading level is defined in HTML, the higher the cascading level.
Reference: thoroughly understand CSS cascading context, cascading level, cascading order, z-index [11]
Values and units
The declaration of CSS consists of properties and values, and there are many types of values:
Numeric value: length value, used to specify values for attributes such as elements width, border-width, font-size, and so on
Percentage: can be used to specify a size or length, such as width, height, or default font-size depending on the parent container
Color: used to specify background-color, color, etc.
Coordinate location: the location of the element with the upper-left corner of the screen as the coordinate origin, such as the common attributes such as background-position, top, right, bottom and left
Function: used to specify the gradient of the resource path or background image, such as url (), linear-gradient (), etc.
And some values need to take units, such as width: 100px, where the px is the unit of length, in addition to px, the more commonly used units of length are em, rem, vw/vh, and so on. So what's the difference between them? When should I use them?
Px
Screen resolution refers to the number of pixels in the horizontal and vertical direction of the screen. For example, the resolution of 1920 × 1080 means that there are 1920 pixels in the horizontal direction and 1080 pixels in the vertical direction.
Px represents the pixels in CSS. In CSS, it is the absolute unit of length and the most basic unit. Other units of length are automatically converted into px by the browser. But for the device, it is actually a relative unit of length, for example, the width and height are all 2px. Under a normal screen, it is actually four pixels, while under the Retina screen with a device pixel ratio (devicePixelRatio) of 2, it has 16 pixels. So when the screen size is the same, the higher the screen resolution is, the more delicate the display effect will be.
At this point, there are some related concepts that need to be sorted out:
Device Pixel (Device pixels)
The physical pixels of the device screen indicate how many pixels there are in the horizontal and vertical direction of the screen; it is similar to the screen resolution.
Device pixel ratio (DPR)
The device pixel ratio indicates that 1 CSS pixel is equal to several physical pixels.
Calculation formula: DPR = physical pixels / logical pixels
The DPR of the current screen can be obtained through window.devicePixelRatio in the browser.
Pixel density (DPI/PPI)
Pixel density is also called display density or screen density, abbreviated as DPI (Dots Per Inch) or PPI (Pixel Per Inch). From a technical point of view, PPI only exists in the field of computer display, while DPI only appears in the field of printing or printing.
Calculation formula: pixel density = pixel size / physical size of the diagonal of the screen
For example, for iPhone 6 with a resolution of 750 * 1334, its pixel density is:
Math.sqrt (750750 + 1334 * 1334) / 4.7 = 326ppi device independent pixels (DIP)
DIP is derived specifically for Android devices because Android screens are so large that they are device-independent. It is calculated based on the screen density, which assumes that when the screen density is 160, px = DIP.
Calculation formula: dip = px * 160 / dpi
Em
Em is one of the relative units of length in CSS. It is actually relative, so who is it relative to? It has two meanings:
In font-size, the font-size size is relative to the parent element, such as the parent element font-size: 16px. When a child element is assigned font-size: 2em, the font size is calculated to be 32px.
Used in other properties relative to its own font size, such as width/height/padding/margin, etc.
We all know that every browser sets a default font-size for the HTML root element html, which is usually 16px. That's why 1em = 16px.
Em calculates layer by layer when calculating, such as:
Div {font-size: 2em;} p {font-size: 2em;}
For the HTML with the above structure, because the font size of the root element html is 16px, the font size calculated by the p tag will be 16 * 2 * 2 = 64px.
Rem
Rem (root em), like em, is a relative unit of length, but rem is relative to html, the root element of HTML.
Because rem is calculated based on html's font-size, it is usually used in adaptive websites or H5.
For example, when doing H5, the front end usually asks UI to give 750px a wide design, and when developing, you can write a page based on the size of iPhone X 375px * 812px, so that you can use the following JS to automatically calculate the base font-size of the root element html based on the viewport width of the current page.
(function (doc, win) {var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window? The width of the design 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; / / bind events with 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 viewport is 375px, the calculated font-size of html will be 100px. What is the advantage of this? The advantage is that it is convenient to write the style. For example, if the header height measured from the design drawing is 50px, then we can write the style directly:
Header {height: 0.5remt;}
Each size measured from the design drawing can be divided into 100 to get the rem value of the current element, without calculation, which is very convenient. To tell you secretly, if you replace the above string of JS code that calculates the html tag font-size with 2, then when calculating the rem, you don't need to divide it by 100. write as many rem as you can measure from the design.
Vw/vh
Vw and vh are units of length relative to the width and height of the on-screen viewport, respectively:
1vw = the width of the viewport is divided into the length of 1 out of 100
1vh = the length of 1 out of 100 viewport heights
In JS, 100vw = window.innerWidth,100vh = window.innerHeight.
The advent of vw/vh has added a way to write adaptive layouts, and developers are no longer limited to rem.
In addition to vw/vh, there are vmin and vmax relative to the viewport:
Vmin: take the smaller value of vw and vh
Vmax: take the higher value of vw and vh
Color system
There are many kinds of values used to represent colors in CSS, enough to form a system, so here is a section to explain it.
According to the color value types mentioned in the CSS color draft [12], they can be roughly divided into these categories:
Color keyword
Transparent keyword
CurrentColor keyword
RGB Color
HSL Color
Color keyword
The color keyword (color keywords) is a case-insensitive identifier that represents a specific color, such as white (white), black (black), etc.
The list of acceptable keywords has changed as CSS evolves:
CSS Standard 1 only accepts 16 basic colors, called VGA colors, because they are derived from the set of colors displayed by VGA graphics cards and are called VGA colors (Video Graphics Array colors).
The orange keyword has been added to CSS standard 2.
From the beginning, browsers accept other colors, and since some early browsers were X11 applications, most of these colors were X11-named color lists, though slightly different. SVG 1.0 was the first standard to formally define these keywords; the CSS color standard 3 also formally defined these keywords. They are often referred to as extended color keywords, X11 colors or SVG colors.
CSS Color Standard 4 adds the rebeccapurple keyword to commemorate web pioneer Eric Meyer.
The following picture shows 16 basic colors, also known as VGA colors. So far, there are a total of 146color keywords in CSS. Here you can see the complete list of color keywords [13].
VGA Color
It is important to note that if the color keyword is wrong when declared, the browser will ignore it.
Transparent keyword
The transparent keyword indicates a completely transparent color, that is, the color will look like a background color. Technically, it is black with the minimum value of the alpha channel, which is short for rgba.
What are the application scenarios for transparent keywords?
Realize the triangle
The following picture is a square filled with 4 borders. If you understand it, you will probably know how to write triangles in CSS.
Div {border-top-color: # ffc107; border-right-color: # 00bcd4; border-bottom-color: # e26b6b; border-left-color: # cc7cda; border-width: 50px; border-style: solid;}
The principle of realizing triangles with transparent:
First of all, the width and height must be 0px, which fills the content through the thickness of the border.
The edges should be colored if they are needed, while the edges that are not needed should be transparent
What kind of triangle you want is completely determined by the position of the colored and transparent edges of the upper and lower left and right sides.
Isosceles triangle: set one side to have color, then the two sides next to it are transparent, and the width is half as wide as the colored side; right triangle: set one side to have color, and then any side next to it is transparent.
Look at the following example:
Increase the click area
Often, the area of the button clicked on the mobile side is very small, but because the actual effect is not good enough to enlarge it, one of the common means is to increase the click area of the button through a transparent border:
.btn {border: 5px solid transparent;} currentColor keyword
CurrentColor takes the current element inherits the text color value of the parent element or the declared text color value, that is, the color value after computed.
For example, for a CSS like this, the border color of the element would be red:
.btn {color: red; border: 1px solid currentColor;} RGB [A] Color
RGB [A] color is a color space composed of R (red)-G (green)-B (blue)-A (alpha).
In CSS, it has two representations:
Hexadecimal symbol
Function character
Hexadecimal symbol
The range of values for each color in RGB is 00~ff, and a higher value indicates a darker color. So a normal color consists of six hexadecimal characters plus #, such as red is # ff0000.
If the RGB color needs to be opaque, you need to add the value of the alpha channel, which is also in the range of 00~ff. For example, a red with an opacity of 67% can be written as # ff0000aa.
When you use a hexadecimal symbol to represent a color, you always use two hexadecimal symbols to represent a color, and if the two characters are the same, you can reduce it to only one, for example, red # f00; red # f00a with 67% opacity.
Function character
When RGB is expressed as a function, the range of each value is 0255,0,100%, so red is rgb (255,0,0), or rgb (100%, 0,0).
If you need to use a function to represent color values with opacity, the range of values is 0 to 1 and the decimal between them or 0% to 100%. For example, red with 67% opacity is rgba (255,0,0,0.67) or rgba (100%, 0%, 0%, 67%).
"it should be noted that the three color values of RGB need to be written consistently, either with numbers or percentages, while opaque values can not be written in the same way as RGB. For example, rgb (100%, 0,0) is invalid, while rgb (100%, 0%, 0%, 0.67) is valid.
In the fourth generation CSS color standard, a new function is added, that is, the separated comma in RGB can be changed to a space, and the comma in RGB and alpha can be changed to /. For example, red with 67% opacity can write rgba (255000 / 0.67). In addition, the writing of rgba is merged into the rgb function, that is, rgb can directly write colors with opacity.
HSL [A] color
HSL [A] color is a color system composed of hue (hue)-saturation (saturation)-luminance (lightness)-opacity.
Hue (H) is the basic attribute of color. The range of values is 0,360 or 0deg~360deg, 0 (or 360) is red, 120 is green, 240 is blue.
Saturation (S) refers to the purity of the color. The higher the color is, the purer the color is, and the lower it is, it gradually turns gray, taking a value of 0%. 0% is gray, 100% panchromatic.
Brightness (L), 0% 100%, 0% dark, 100% white.
Opacity (A), take 0: 100%, or 0: 1 and the decimal
You can refer to RGB in writing, but the values of the parameters are different.
Set a button to write a red color with an opacity of 67%, and all of the following have the same effect:
Button {color: # ff0000aa; color: # f00a; color: rgba (255,0,0,0.67); color: rgb (100% 0% / 67%); color: hsla (0,100%, 50%, 67%); color: hsl (0deg 100% / 67%);}
Tip: in Chrome DevTools, you can press and hold shift + the left mouse button to toggle the color representation.
Media inquiry
Media query refers to the customization of the style of the website according to different devices, specific device characteristics or parameters.
You can specify which devices the style file can only work for by adding a media attribute. If it is not specified, it defaults to all, that is, it works for all devices:
Which device types are supported?
All: for all Devic
Print: suitable for paging materials and documents viewed on screen in print preview mode
Screen: mainly used for screen
Speech: mainly used in speech synthesizer.
"it is important to note that although the resource specified through media does not match its device type, the browser will still load it.
In addition to letting the specified device take effect, you can also use @ media to make the CSS rule take effect under certain conditions. Responsive pages use @ media to make a page suitable for both PC, Pad and mobile.
@ media (min-width: 1000px) {}
Media queries support logical operators:
And: takes effect only when the query conditions are met
Not: the query condition is reversed
Only: takes effect only when the entire query matches. The common phrase is compatible with the old browser, and the media type must be specified when using it.
Comma or or: match if one of the query conditions is met
Media query also supports a number of media features [14], allowing it to write very complex query conditions:
/ * minimum height of user equipment is 680px or screen device in portrait mode * / @ media (min-height: 680px), screen and (orientation: portrait) {} Common requirements Custom attributes
In the past, variables were usually used in preprocessors, but now the use of variables is also supported in CSS. Through custom properties, you can reference it where you want to use it.
Custom attributes are as cascading as ordinary attributes, declaring that they are available within the scope of the full document when they are under: root, while if they are declared under an element, they can only be used under it and its child elements.
Custom attributes must be declared in the format-- x, for example:-- theme-color: red; requires the var function when using custom attributes. For example:
: root {--theme-color: red;} H2 {color: var (--theme-color);}
The figure above is the box-shadow of the dynamic adjustment element implemented by using CSS custom attributes with JS, as shown in this codepen demo.
1px Border solution
The Retina screen has a higher resolution than an ordinary screen, so the 1px frame on the mobile side will look thicker, and this line usually needs to be refined in order to look beautiful. Here is an article listing 7 Chinese cases for reference: 7 ways to solve the 1px frame problem of mobile Retina screen [15]
Here is the last relatively perfect solution implemented through pseudo-classes and transform:
Set only 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: 00; transform-origin: 00;}
Set 4 borders at the same time:
.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;} clear floats
What is a float: a floating element leaves the document stream and floats left / right until it encounters a parent element or another floating element.
Why float clearly and what problems does it cause?
Because the floating element will deviate from the normal document flow and will not occupy the position of the document flow, if there are floating elements below a parent element, then the parent element cannot be stretched apart by the floating element, so the parent element loses its height. This is the so-called problem of height collapse of the parent element caused by floating.
Once the height of the parent element collapses, it will affect the layout of the subsequent elements. in order to solve this problem, you need to clear the float and restore the height of the parent element. what should you do?
Here are two methods: clear through BFC and clear through clear.
BFC clear float
As mentioned earlier in the introduction to BFC, the height of the floating child element is also taken into account when calculating the height of the BFC, and you can float clearly using this rule.
Suppose that there are only 2 child elements child inside a parent element parent, and they are all floating on the left. If parent does not set the height at this time, because the floating causes a height collapse, the height of the parent will be 0. At this time, as long as a BFC is created for the parent, its height can be restored.
There are many ways to generate BFC. We can simply implement BFC clearing floats by setting overflow: auto to the parent element, but it is better to use overflow: hidden for compatibility with IE.
.parent {overflow: hidden;}
Clearing floats through overflow: hidden is not perfect and is truncated when the element is shaded or there is a drop-down menu, so the use of this method is limited.
Clear floats through clear
Let me first post the conclusion:
.clearfix {zoom: 1;} .clearfix:: after {content: "; display: block; clear: both;}
The core principle of this writing is through: after pseudo-element to generate an empty block-level element after the last child element of the parent element, and then move this pseudo-element to the back of all the floating elements before it through clear, and draw a diagram to understand it.
You can combine this codepen demo to understand the clear clear floating principle in the above figure.
In order to show the need, the content of the pseudo element is set to:: after in the above demo or figure. In actual use, it needs to be set to an empty string with a height of 0, so that the height of the parent element is supported by the actual child element.
This method is basically used by everyone to clear the floating scheme, which is very common.
Reference: floating and clearing floats in CSS, comb through [16]
Eliminate browser default styl
Different browsers often behave differently for the same type of HTML tags, so when creating a website, developers usually need to clear the default style of these browsers so that the pages can be consistent on different browsers.
Eric A. Meyer, the master of CSS, did it a long time ago to clear the default style of the browser. It's all about writing a bunch of generic styles to reset the browser's default styles, which are usually placed in a file named reset.css. For example, the master's reset.css [17] reads like this:
Html, body, div, span, applet, object, iframe, h2, h3, h4, h5, h6, h7, 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;}
His reset.css is said to be the most widely used restyling scheme.
In addition to reset.css, then came Normalize.css [18]. About Normalize.css, its author necolas wrote a special article about it and talked about the difference between it and reset.css. This is the translation of the article he wrote: let's talk about Normalize.css [19].
The article introduces that Normalize.css is just a small CSS file, but it provides a high degree of consistency across browsers on the default HTML element style. Compared to traditional CSS reset,Normalize.css, which is a modern and high-quality alternative for HTML5, it is now used by many well-known frameworks and websites.
For the specific style of Normalize.css, please see Normalize.css here.
Different from reset.css,Normalize.css, it has the following characteristics:
Reset.css sets the default style for almost all tags, while Normalize.css selectively protects some valuable default values
Fixed bug in many browsers, which reset.css failed to do
Will not let your debugging tools become cluttered, on the contrary, reset.css because of setting a lot of default values, so in the browser debugging tools often see a lot of inheritance styles, appears to be very messy
Normalize.css is modular, so you can selectively remove parts that will never be used, such as the generalization of the form
Normalize.css has detailed documentation
Default for long text processing: characters are too long to overflow the container
Character breaks beyond part of the line
Use hyphens when characters are out of position
Single-line text exceeds ellipsis
Multi-line text exceeds ellipsis
Check out the above examples of these scenarios: codepen demo
What do you mean a whole piece of text? For example, the following technical tag belongs to the whole piece of text:
In addition, he also did a compatible treatment of iOS/Safari, interested in reading the next: CSS whole block of text overflow ellipsis features explore [20].
Horizontal and vertical center
There are only two cases in which the element is centered horizontally and vertically in the parent element:
Single-line text, inline, or inline-block elements
Block box with fixed width and height
Block-level box with unfixed width and height
Here is a codepen demo with all the horizontal and vertical centering schemes listed below, which works better with the example.
Single-line text, inline, or inline-block element
Horizontal center
If such an element needs to be centered horizontally, the parent element must be a block-level element (block level), and the parent element needs to be styled like this:
.parent {text-align: center;} is centered vertically
Method 1: achieve the effect of vertical centering by setting the same distance between the upper and lower parts:
.single-line {padding-top: 10px; padding-bottom: 10px;}
Method 2: achieve vertical centering by setting height and line-height to be consistent:
.single-line {height: 100px; line-height: 100px;}
Block box with fixed width and height
Method 1: absolute + negative margin
Method 2: absolute + margin auto
Method 3: absolute + calc
Block level box method with unfixed width and height: absolute + transform
Method 2: line-height + vertical-align
Method 3: writing-mode
Method 4: table-cell
Method 5: flex
Method 6: grid
Commonly used layout two-column layout (sidebar width-fixed main column adaptive)
Several examples are written for the following scenarios: codepen demo
Method 1: float + overflow (BFC principle)
Method 2: float + margin
Method 3: flex
Method 4: grid
Three-column layout (the width of the main column on both sides is self-adaptive)
Several examples are written for the following scenarios: codepen demo
Method 1: holy Grail layout
Method 2: double wing layout
Method 3: float + overflow (BFC principle)
Method 4: flex
Method 5: grid
Multi-column contour layout method 1: padding + negative margin
Method 2: set the parent background picture
Three-line layout (self-adaptive head-to-tail height main column)
Four methods are listed, all of which are based on the following HTML and CSS, and the reading effect is better with examples: codepen demo
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 4: grid
Used within the element.
Note: the value must be wrapped in double quotation marks, and
Thank you for your reading, the above is the content of the "summary of the core knowledge points of CSS". After the study of this article, I believe you have a deeper understanding of the summary of the core knowledge points of CSS, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.