Recently, I have arranged the high frequency test questions on the front face and shared them with you to learn. If you have any questions, please correct me!
Note: 2021.5.21 has been updated to modify some errors in this article. Add mind map, according to my own interview experience and the interview experience on platforms such as Niuke.com, generally distinguish the frequency of examination of interview questions, so as to make targeted review.
The following is a series of articles.
[1] “2021” high frequency front face test summary HTML article
[2] “2021” high-frequency front end of the CSS section
[3] 2021
[4] 2021
[5] “2021”
[6] “2021”
【7】 “2021” High-Frequency front end test questions summary
[8] “2021” high frequency front end test questions summary
[9] “2021” high frequency front end test question summary of computer network article
[10] “2021” high frequency front end test summary of browser principles
[11] the performance optimization of “2021” high frequency test paper summary
[12] “2021” high frequency front end of the handwritten code of the test summary
[13] “2021” high frequency front end test summary code output results
First, CSS foundation
1. CSS selectors and their priorities
The selector | format | Priority weight |
---|---|---|
The id selector | #id | 100 |
Class selectors | #classname | 10 |
Property selector | A [ref = “eee”] | 10 |
Pseudo-class selector | li:last-child | 10 |
Label selector | div | 1 |
Pseudo-element selector | li:after | 1 |
Adjacent sibling selector | h1+p | 0 |
Child selectors | ul>li | 0 |
Descendant selector | li a | 0 |
Wildcard selector | * | 0 |
For the priority of the selector:
- Label selectors, pseudo-element selectors: 1
- Class selectors, pseudo-class selectors, property selectors: 10
- Id selector: 100
- Inline style: 1000
Notes:
- ! Styles declared important have the highest priority;
- If the priorities are the same, the last appearing style takes effect;
- Inherited styles have the lowest priority;
- The universal selector (*), sub-selector (>), and neighboring sibling selector (+) are not in these four levels, so they all have a weight of 0;
- When the source of the style sheet is different, the priority order is: inline style > Internal Style > External Style > Browser custom style > Browser default style.
2. What are the inheritable and non-inheritable properties of the CSS
1. The attribute of non-inheritance
- Display: Specifies the type of box that the element should generate
- Text properties:
- Vertical-align: aligns the vertical text
- Text-decoration: Specifies the decoration to be added to the text
- Text-shadow: indicates the text shadow effect
- White-space: The processing of white space
- Unicod-bidi: Sets the direction of the text
- Box model properties: width, height, margin, border, padding
- Background attributes: background, background-color, background-image, background-repeat, background-position, background-attachment
- Position properties: float, clear, position, top, right, bottom, left, min-width, min-height, max-width, max-height, overflow, clip, z-index
- Generate content properties: Content, counter-reset, counter-increment
- Outline style properties: outline-style, outline-width, outline-color, outline
- Page style properties: size, page-break-before, page-break-after
- Sound style properties: pause-before, pause-after, pause, cue-before, cue-after, cue, play-during
Second, the property of inheritance
- Font family properties
- Word-break: break-word! Important
- Text-weight: the weight of the font
- Font-size: indicates the size of the font
- Word-wrap: break-word! Important
- Text series attribute
- Text-indent: Indicates the indent of text
- Text-align: horizontal text alignment
- The line – height: line height
- Word-spacing: Indicates the spacing between words
- Letter-spacing: Indicates the spacing between Chinese characters or letters
- Texttransform: Changes the wrapper of the text (uppercase, lowercase and capitalize)
- Color: Text color
- Element visibility
- Visibility: indicates that the control element is displayed and hidden
- List layout property
- List-style: indicates the list style, including list-style-type and list-style-image
- The cursor attributes
- Cursor: Specifies the cursor state
3. The value of the display attribute and its function
Attribute values | role |
---|---|
none | The element is not displayed and is removed from the document flow. |
block | Block types. The default width is the width of the parent element, width and height can be set, and the display is newline. |
inline | Inline element type. The default width is the content width. The width and height cannot be set. |
inline-block | The default width is the content width. You can set the width and height to display in the same line. |
list-item | Display as block type elements and add style list tags. |
table | This element is displayed as a block-level table. |
inherit | Specifies that the value of the display attribute should be inherited from the parent element. |
4. Differences between display block, inline, and inline-block
(1) Block: an exclusive row, multiple elements will be on another row, width, height, margin and padding properties can be set;
(2) Inline: The element does not occupy a single line. Setting the width and height properties is invalid. You can set the horizontal margin and padding properties, but not the vertical padding and margin.
(3) inline-block: An object is set to inline, but its contents are rendered as a block object. Subsequent inline objects are lined up on the same line.
For inline and block-level elements, the characteristics are as follows:
(1) Inline elements
- Set width and height invalid;
- You can set the horizontal margin and padding properties, but not the vertical padding and margin.
- It does not wrap lines;
(2) Block-level elements
- Width and height can be set;
- Both margin and padding are valid;
- You can wrap lines;
- Multiple blocks, arranged from top to bottom by default.
5. What are the ways to hide elements
- Display: None: The render tree does not contain the render object, so the element does not take up position on the page and does not respond to bound listener events.
- Visibility: hidden: indicates that the element still occupies space on the page but does not respond to the bound listening event.
- Opacity: 0: The opacity of the element is set to 0 to hide the element. Elements still occupy space on the page and can respond to listener events bound to the element.
- Position: Absolute: Concealment of an element by removing it from the visual area using absolute positioning.
- Z-index: negative value: hides the element by hiding it from other elements.
- Clip /clip-path: Element clipping is used to hide elements. In this method, the element still occupies its place on the page, but does not respond to bound listener events.
- Transform: scale(0,0) : scale the element to 0 to hide the element. In this way, the element still takes its place on the page, but it does not respond to the bound listener event.
6. The difference between link and @import
Both are external references to CSS. The differences are as follows:
- Link is an XHTML tag that, in addition to loading CSS, can define other transactions such as RSS; @import belongs to the CSS category and can only load CSS.
- When the link references the CSS, it is loaded at the same time as the page is loaded. @import requires the page to load after the page is fully loaded.
- Link is an XHTML tag, no compatibility issues; @import was introduced in CSS2.1 and is not supported by earlier browsers.
- Link supports using Javascript to control the DOM to change styles; @import is not supported.
7. The difference between transition and animation
- Transition is a property that emphasizes the importance of an animation. Its implementation requires an event (mouse move, focus, click, etc.) to be triggered before the animation is executed. It is similar to flash tween animation, with a start keyframe and an end keyframe.
- Animation is an animation property. Its implementation does not need to trigger an event, it can execute itself after a set time, and it can loop an animation. It is also similar to Flash’s tween animation, but it can set multiple keyframes (defined with @keyframe) to complete the animation.
8. Display: None and visibility: the difference between hidden
Both of these attributes make the element hidden, invisible. The differences are as follows:
(1) In the render tree
display:none
Elements completely disappear from the render tree, rendering without taking up any space;visibility:hidden
Elements will not disappear from the rendered tree. Rendered elements will still take up space, but the content will not be visible.
(2) Whether the attribute is inherited
display:none
If the attribute is not inherited, the descendant node will disappear from the render tree along with the parent node, and the attribute of the descendant node will not be displayed by modifying the attribute.visibility:hidden
Is an inheritance property, the descendant node is lost because of inheritancehidden
, by settingvisibility:visible
Can let the descendant node display;
(3) Modifying the display of the element in the general document flow will usually result in the rearrangement of the document, but modifying the visibility attribute will only result in the redrawing of the element;
(4) If the screen reader is used, the contents set to display: None will not be read, and the contents set to visibility:hidden will be read.
9. What are the differences between pseudo-elements and pseudo-classes?
- Pseudo-elements: Insert additional elements or styles before and after content elements that are not actually generated in the document. They are only externally visible, but they are not found in the source code of the document and are therefore called “pseudo-” elements. Such as:
p::before {content:"Chapter one:"; }p::after {content:"Hot!"; }p::first-line {background:red; }p::first-letter {font-size:30px; }Copy the code
- Pseudo-class: Adds special effects to specific selectors. It adds categories to existing elements and does not create new elements. Such as:
a:hover {color: #FF00FF}
p:first-child {color: red}
Copy the code
Conclusion: Pseudo-class changes the element state by adding pseudo-class to element selector, while pseudo-element changes the element by operating on the element.
10. Understanding requestAnimationframe
There are many ways to achieve the animation effect. In Javascript, you can use setTimeout timer to achieve it. In CSS3, you can use Transition and animation to achieve it. In addition, HTML5 provides a requestAnimationFrame API dedicated to request animation, which, as the name implies, is a requestAnimationFrame.
MDN description of this method:
Tell the browser window. RequestAnimationFrame () – you want to perform an animation, and required the browser until the next redraw calls the specified callback function to update the animation. This method needs to be passed a callback function as an argument, which will be executed before the browser next redraw.
Grammar: window. RequestAnimationFrame (the callback); Callback is the function called to update the animation frame before the next redraw. The callback function is passed the DOMHighResTimeStamp parameter, which indicates the time requestAnimationFrame() started to execute the callback function. This method is a macro task, so it is executed after the microtask has been executed.
CancelAnimationFrame () cancelAnimationFrame() cancelAnimationFrame() cancelAnimationFrame() cancelAnimationFrame() cancelAnimationFrame() cancelAnimationFrame() cancelAnimationFrame() cancelAnimationFrame
Advantage:
- CPU power saving: Animation implemented using SetTinterval. When the page is hidden or minimized, SetTinterval still animates in the background. Since the page is invisible or unavailable, there is no point in refreshing the animation and it is a waste of CPU resources. RequestAnimationFrame is completely different. When the page is not active, the screen refresh task of the page is also paused by the system, so the RequestAnimationFrame that follows the system will also stop rendering. When the page is active, the animation will continue where it left off. It effectively saves CPU overhead.
- Function throttling: In high frequency events (resize, Scroll, etc.), in order to prevent multiple function executions within a refresh interval, RequestAnimationFrame guarantees that the function is only executed once per refresh interval, which not only ensures smoothness, but also better saves the cost of function execution. It doesn’t make sense to execute the function multiple times within a refresh interval, because most monitors refresh every 16.7ms, and multiple draws don’t show up on the screen.
- Reduced DOM operations: The requestAnimationFrame aggregates all DOM operations in each frame in a single redraw or backflow, and the redraw or backflow intervals closely follow the browser refresh rate, which is generally 60 frames per second.
The downside of setTimeout animation is that it keeps changing the position of the image by setting the interval. However, it is easy to appear the phenomenon of stalling and shaking; The reason is:
- The setTimeout task is placed in an asynchronous queue, and is executed only when the main thread is finished, so the actual execution time is always later than the settime.
- The fixed interval of setTimeout is not necessarily the same as the screen refresh interval, which can cause frame loss.
11. Understanding of box model
There are two types of box models in CSS3: standard box model and IE box modelThe box model is composed of four parts, namely margin, border, padding and content.
The difference between standard box model and IE box model is that when setting width and height, the corresponding range is different:
- The width and height properties of the standard box model contain only content,
- The scope of the WIDTH and height properties of the IE box model includes border, padding, and content.
You can change the box model of an element by modifying its box-sizing property:
box-sizeing: content-box
Represents the standard box model (default)box-sizeing: border-box
Represents the IE box model (weird box model)
12. Why do you use it sometimestranslateTo change position instead of positioning?
Translate is a value of the Transform property. Changing Transform or Opacity does not trigger reflow or repaint in the browser, only Compositions. Changing absolute positioning triggers relayout, which in turn triggers redrawing and recomposing. Transform lets the browser create a GPU layer for the element, but changing the absolute positioning uses CPU. Translate () is therefore more efficient and can reduce the drawing time for smooth animations. While translate changes position, the element still occupies its original space, which does not happen with absolute positioning.
13. What causes the invisible gap between Li and Li? How to solve it?
Browsers render white space characters (Spaces, newlines, tabs, and so on) between inline elements as a single space. For aesthetics, a
The solution:
(1) Set float:left for
(2) Write all
-
Disadvantages: Other character sizes in
-
are also set to 0, additional character sizes need to be resized, and empty Spaces will still appear in Safari.
14. What new features are in CSS3
- New CSS selectors (: not(.input) : all nodes whose class is not “input”)
- Rounded corners (border-radius:8px)
- Multi-column layout
- Shadow and Reflection (Shadoweflect)
- Text-shadow
- Text-decoration
- Linear gradient
- Transform
- Added rotation, Zoom, position, Tilt, animation, and multiple backgrounds
15. Concept and calculation rules of replacement elements
An element that can be replaced by modifying the content rendered by an attribute value is called a replacement element.
In addition to the fact that the content is replaceable, the replacement element has the following properties:
- The appearance of the content is not affected by the CSS on the page: in professional terms, the style is represented outside the scope of the CSS. How to change the appearance of the replacement element itself requires something like the appearance attribute, or some style interface that the browser itself exposes.
- Have its own size: In the Web, many replacement elements have a default size (excluding borders) of 300 pixels by 150 pixels without a specific size setting, as in
- Many CSS properties have their own set of rules: the most typical is the vertical-align attribute, which is interpreted differently for replacement and non-replacement elements. For example, the default vertical-align value baseline is defined as the bottom edge of the x character, while the replacement element baseline is defined as the bottom edge of the element.
- All replacement elements are inline horizontal: that is, replacement elements and replacement elements, replacement elements and text can be displayed on a single line. However, the default display value for the replacement element is different, either inline or inline-block.
The dimensions of replacement elements are divided into three categories from the inside out:
- Proper size: refers to the original size of the replacement content. For example, images and videos have their own width and height when they exist as separate files.
- HTML size: Can only be changed using the HTML native properties, which include width and height, and the size attribute.
- CSS size: Specifies the size that can be set by width and height or max-width/min-width and max-height/min-height of the CSS, corresponding to the content box in the box size.
(1) If CSS and HTML dimensions are not available, the proper dimensions are used as the final width and height. (2) If there is no CSS size, use the HTML size as the final width and height. (3) If there is a CSS size, the final size is determined by the CSS properties. (4) If “proper size” contains an inherent width to height ratio and only width or only height is set, the element is still displayed in accordance with the inherent width to height ratio. (5) If none of the above conditions is met, the final width is 300 pixels and the height is 150 pixels. (6) Inline replacement elements and block-level replacement elements use the same set of size calculation rules as above.
16. Common picture formats and usage scenarios
(1) BMP, is lossless, support both index color and direct color lattice diagram. There is little compression of the data in this image format, so BMP images are usually larger files.
(2) GIF is a lossless, indexed color lattice diagram. LZW compression algorithm is used for coding. The small file size is an advantage of the GIF format, as well as support for animation and transparency. However, THE GIF format only supports 8bit indexed colors, so the GIF format is suitable for scenarios that have low color requirements and require small file size.
(3) JPEG is lossy, using direct color bitmap. JPEG images have the advantage of using direct colors. Thanks to the richer colors, JPEG is very good for storing photos. Compared to GIF, JPEG is not good for storing business logos, wireframe images. Because lossy compression will cause the image to be blurred, and direct color selection will cause the image file to be larger than GIF.
(4) PNG-8 is a lossless bitmap with indexed colors. PNG is a relatively new image format, and PnG-8 is a very good alternative to GIF. Whenever possible, use PNG-8 instead of GIF as it has a smaller file size for the same image. In addition, PnG-8 also supports transparency adjustment, which GIF does not. Unless animation support is required, there is no reason to use GIF instead of PNG-8.
(5) PNG-24 is a lossless bitmap using direct color. The advantage of PNG-24 is that it compressions the image data, making pNG-24 files much smaller than BMP files for the same effect. Of course, PNG24 is still much larger than JPEG, GIF, or PNG-8.
(6) SVG is a lossless vector graph. SVG is a vector graph, meaning that AN SVG image consists of lines and curves and the methods used to draw them. When you zoom in on an SVG image, you still see lines and curves, not pixels. SVG images do not distort when enlarged, so it is suitable for drawing logos, ICONS, etc.
(7) WebP is a new image format developed by Google. WebP is a bitmap that supports both lossless and lossless compression and uses direct color. As you can see from the name, it was made for the Web. What is made for the Web? This means that WebP has a smaller file size for the same quality of images. There are a lot of images on the web right now, and if you can reduce the file size of each image, you can greatly reduce the amount of data transfer between the browser and the server, thereby reducing access latency and improving the access experience. Currently, only Chrome and Opera browsers support WebP, which is not very compatible.
- In the case of lossless compression, WebP images of the same quality, the file size is 26% smaller than PNG;
- In the case of lossy compression, the file size of WebP images with the same image accuracy is 25%~34% smaller than that of JPEG.
- WebP image format supports image transparency. A lossless compressed WebP image requires only 22% extra file size to support transparency.
17. Understanding of CSSSprites
CSSSprites, all the images involved in a page are included in a large image, and then use the CSS background-image, background-repeat, background-position attribute combination for background positioning.
Advantages:
- using
CSS Sprites
Can very well reduce the HTTP requests of web pages, thus greatly improving the performance of the page, which isCSS Sprites
The greatest advantage; CSS Sprites
Can reduce the number of bytes in the picture, the number of bytes to merge 3 pictures into 1 picture is always less than the sum of the three pictures.
Disadvantages:
- When merging pictures, it is necessary to combine multiple pictures into one picture in an orderly and reasonable way, and to leave enough space to prevent unnecessary background appearing in the plate. In the widescreen and high resolution adaptive page, if the background is not wide enough, it is easy to break the background;
CSSSprites
At the time of development is relatively a bit of trouble, need to usephotoshop
Or other tools to measure the exact position of each background cell.- Maintenance:
CSS Sprites
When maintenance is more troublesome, the page background has a little change, it is necessary to change the merged picture, do not change the place as far as possible, so as to avoid more changesCSS
If you can’t fit it in the original place, you can only (preferably) add the image below, so that the number of bytes of the image is increased, and you need to change itCSS
.
18. What are physical pixels, logical pixels and pixel density, and why do we need @3X, @2X images for mobile development?
In the iPhone XS, for example, when writing CSS code, the width of the unit px is 414px & 896px. This means that when you give a DIV element a width of 414px, it will fill the width of the phone.
If you had a ruler to actually measure the phone’s physical pixels, it would be 1242 by 2688; The calculation shows that 1242/414=3, that is, on one side, one logical pixel =3 physical pixels, which means that the pixel density of the screen is 3, which is often called 3 times the screen.
For pictures, in order to ensure that there is no distortion, one picture pixel should correspond to at least one physical pixel. If the original picture is 500,300 pixels, then a picture of 1500,900 pixels should be put on the 3x screen to ensure that one physical pixel corresponds to at least one picture pixel, so that there is no distortion.Of course, it is possible to provide only the highest definition images for all screens. Although low-density screens don’t use as many image pixels, and can waste bandwidth and delay downloading extra pixels, the result is that the image is not distorted on all screens.
You can also use CSS media queries to determine different pixel densities to select different images:
my-image { background: (low.png); }
@media only screen and (min-device-pixel-ratio: 1.5) {
#my-image { background: (high.png); }}Copy the code
19. Usage scenarios of Margin and padding
- If you need to add a margin outside the border and the margin does not need a background (color), use margin.
- Use padding when you need to add white space inside the border test and the white space requires a background (color).
Of 20.Understanding of line-height and how to assign it
(1) The concept of line height:
- Line-height refers to the height of a line of text, including the word spacing, which is actually the distance from the next baseline to the previous baseline;
- If a tag does not define a height attribute, the final height of the tag is determined by a line-height.
- If the height of a container is not set, it is the line-height that opens the container, not the text inside the container.
- Setting the word-height value to a height value can achieve vertical center of a single line of text;
- Both line-height and height can be extended to a height;
(2) The value of line height:
- The em will calculate its own row height based on the parent element’s font-size value
- Pure numbers: will pass on the proportion to future generations. For example, if the parent row height is 1.5 and the child element font is 18px, then the child element row height is 1.5 * 18 = 27px
- Percentage: Passes the calculated value to future generations
21. What are the methods of CSS optimization and performance improvement?
Loading performance:
(1) CSS compression: The written CSS is packaged and compressed to reduce the file size.
Margin :top 0 bottom 0; margin:top 0 bottom 0; But the margin – bottom: bottom; margin-left:left; Execution will be more efficient.
(3) Reduce the use of @import and suggest using link, because the latter is loaded together when the page is loaded, while the former is loaded after the page is loaded.
Selector performance:
(1) Key selector. The last part of the selector is the key selector (that is, the part used to match the target element). CSS selectors match from right to left. When using a descendant selector, the browser iterates through all the child elements to see if they are the specified element, etc.
(2) Do not tag a rule if it has an ID selector as its key selector. Filter out irrelevant rules (so the style system doesn’t waste time matching them).
(3) Avoid using wildcard rules, such as *{}, the number of calculations is amazing, only the elements needed to be selected.
(4) Select as few tags as possible and use class instead.
(5) Use the descendant selector as little as possible to reduce the weight value of the selector. Descendant selectors have the highest overhead. Try to keep selector depth to a minimum, up to no more than three levels, and use more classes to associate each tag element.
(6) Know which attributes can be inherited, and then avoid repeating rules for those attributes.
Rendering performance:
(1) Use high-performance attributes: float and location with caution.
(2) Minimize page rearrangement and redrawing.
(3) Empty rule: {}. The reason for empty rules is generally to reserve styles. Removing these empty rules can definitely reduce the size of CSS documents.
(4) When the attribute value is 0, no unit is added.
(5) The value of the attribute is a floating decimal 0.**, and the 0 before the decimal point can be omitted.
(6) Standardize various browser prefixes: those with browser prefixes come first. Standard properties follow.
(7) Do not use the @import prefix, which affects CSS loading speed.
(8) Optimize the nesting of selectors to avoid too deep a level.
(9) CSS Sprite diagram, the same page similar parts of the small icon, easy to use, reduce the number of page requests, but at the same time the image itself will become larger, when using, consider the advantages and disadvantages clearly, and then use.
(10) Use the display property correctly. Because of display, certain style combinations will be invalid, increasing the size of the style and affecting the parsing performance.
(11) Don’t abuse Web fonts. WebFonts may be unfamiliar to Chinese websites, but they are very popular abroad. Web Fonts are often bulky, and some browsers block page rendering damage when downloading Web Fonts.
Maintainability, robustness:
(1) Pull out styles with the same attributes, integrate them and use them in the page through classes to improve the maintainability of CSS.
(2) Style and content separation: CSS code is defined in external CSS.
22. What is the CSS preprocessor/post-processor? Why use them?
Preprocessors, such as less, sass, and stylus, are used to precompile sass or less, increasing the reuse of CSS code. Hierarchies, mixins, variables, loops, functions, and so on are extremely convenient for writing and developing UI components.
A post-processor, such as postCss, usually processes THE CSS according to the CSS specification in the finished stylesheet to make it more efficient. By far the most common approach is to add browser private prefixes to CSS properties to address cross-browser compatibility issues.
The CSS preprocessor adds some programming features to the CSS without considering the compatibility of browsers. It allows the CSS to use basic programming features such as variables, simple logic programs, and functions in a programming language, making the CSS more concise and improving adaptability, readability, and maintainability.
Other CSS preprocessor languages: Sass (Scss), Less, Stylus, Turbine, Swithch CSS, CSS Cacheer, DT CSS.
Reasons for use:
- The structure is clear and easy to expand
- It is convenient to mask differences in browser private syntax
- Multiple inheritance can be easily implemented
- Perfect compatibility
CSS
Code that can be applied to old projects
What’s the difference between double colons and single colons for before and after?
(1) Colons (:) are used for CSS3 pseudo-classes, and double colons (::) are used for CSS3 pseudo-elements. (2) ::before is a pseudo-element defined before the body of the element in the presence of a child element. It doesn’t exist in the DOM, it only exists in the page.
Note that the :before and :after pseudo-elements are new in CSS2.1. Originally, pseudo-elements were prefixed using a single colon syntax, but as the Web evolved, in the CSS3 specification, the syntax of pseudo-elements was modified to use double colons, becoming ::before, ::after.
24. Display: Inline-block when will the gap be displayed?
- When there is space, there is a gap, you can delete the space to solve;
margin
When it’s positive, you can make itmargin
Use negative values;- use
font-size
, you can setfont-size:0
,letter-spacing
,word-spacing
To solve;
25. Single and multiple lines of text overflow hide
- Single line text overflow
overflow: hidden; // Overflow hidetext-overflow: ellipsis; // Overflow is displayed with an ellipsiswhite-space: nowrap; // Specifies that the text in a paragraph is not newlineCopy the code
- Multiple lines of text overflow
overflow: hidden; // Overflow hidetext-overflow: ellipsis; // Overflow is displayed with an ellipsisdisplay:-webkit-box; // Display as elastic flex box model. -webkit-box-orient:vertical; // Set telescreen box's children to be arranged vertically from top to bottom -webkit-line-clamp:3; // Number of lines to displayCopy the code
Note: Since the above three properties are CSS3 properties, no browser will be compatible, so add the -webkit- to the front to make some browsers compatible.
26. What is Sass, Less? Why use them?
They are both CSS preprocessors, a kind of abstraction layer on top of CSS. They are a special syntax/language compiled into CSS. For example, Less is a dynamic style language, which gives CSS dynamic language features such as variables, inheritance, calculations, and functions. Less can be run on both the client side (IE 6+, Webkit, Firefox) and the server side (with Node.js).
Why use them?
- The structure is clear and easy to expand. You can easily mask browser-private syntax differences. Encapsulate the repetitive processing of browser syntax differences, reducing meaningless mechanical labor.
- Multiple inheritance can be easily implemented. Fully compatible with CSS code, which can be easily applied to older projects. LESS simply extends the CSS syntax, so older CSS code can be compiled with LESS code.
27. Understanding of media queries?
A media query consists of an optional media type and zero or more expressions that limit the scope of the stylesheet using media capabilities, such as width, height, and color. Media queries, added from CSS3, allow the presentation of content to be tailored to a specific range of output devices without changing the content itself, adapting web pages to respond to different models of devices.
The media query contains an optional media type and zero or more expressions describing the characteristics of the media that will eventually resolve to true or false if the CSS3 specification is met. The media query results in true if the media type specified in the media query matches the device type used to display the document and all expressions are true. Then the style in the media query will take effect.
<! CSS media query in link element --><link rel="stylesheet" media="(max-width: 800px)" href="example.css" /><! CSS media query in style sheet --><style>
@media (max-width: 600px) {
.facet_sidebar {
display: none; }}</style>
Copy the code
Simply put, using the @media query, you can define different styles for different media types. @media can be useful for different screen sizes, especially for pages that are designed to be responsive. While resizing the browser, the page also rerenders the page according to the width and height of the browser.
28. Understanding of CSS engineering
CSS engineering is designed to solve the following problems:
- Macro design: how is the CSS code organized, how is it split, how is the module structure designed?
- Coding optimization: How to write better CSS?
- Build: What to do with my CSS so that it is best packaged?
- Maintainability: When code is written, how do you minimize the cost of subsequent changes to it? How can you make sure that any one of your colleagues can easily take over?
The following three directions are the current more popular, very good general CSS engineering practices:
- Preprocessor: Less, Sass, etc.
- Important engineering plug-ins: PostCss;
- Webpack loader, etc.
Based on these three directions, some typical subproblems can be derived. Here we will look at them one by one:
(1) Preprocessor: Why use a preprocessor? What problem was it created to solve?
The preprocessor is actually the “wheel” of the CSS world. The preprocessor allows us to write a language that looks like CSS, but isn’t really CSS, and then compile it into CSS code:So why write “class CSS” when you can write CSS code so well? This is the same as writing React’s JSX or Vue template syntax when you could have done everything with JS. To see how much fun it is to have a preprocessor, the first thing you need to know is how bad traditional CSS is. As the complexity of front-end services increases, front-end engineering requirements for the CSS are as follows:
- Macro design: we hope to optimize the directory structure of CSS files, to achieve reuse of existing CSS files;
- Coding optimization: we want to write a clear structure, concise and easy to understand CSS, it needs to have a clear nested hierarchical relationship, rather than undifferentiated one to the bottom writing method; We want it to be more programmable with variable characteristics, computing power, cyclic power and so on, so that we can write less useless code;
- Maintainability: More programmability means a better code structure, and reuse means a simpler directory structure and more scalability, both of which naturally lead to more maintainability.
These are three things that traditional CSS can’t do, and that the preprocessor solves. Preprocessors generally have the following features:
- The ability to nest code to reflect the hierarchical relationship between different CSS properties;
- Support for defining CSS variables;
- Provide a calculation function;
- Extend and mixin code snippets
- Support the use of loop statements;
- CSS files can be modular for reuse.
(2) PostCss: How does PostCss work? In what scenarios do we use PostCss?
It differs from the preprocessor in that the preprocessor deals with class CSS, while PostCss deals with CSS itself. Babel can convert a higher version of JS code to a lower version of JS code. PostCss does a similar thing: it compiles advanced CSS syntaxes that are not yet widely supported by browsers, and it automatically prefixes some syntaxes that require additional compatibility. Even better, PostCss is greatly enhanced by its powerful plug-in mechanism, which supports a wide variety of extensions.
The PostCss can be used in many scenarios:
- Improved readability of CSS code: PostCss can actually do things similar to what a preprocessor can do;
- PostCss’s Autoprefixer plug-in allows us to automatically add browser prefixes when our CSS code needs to be used with earlier browsers;
- Allows us to write future-oriented CSS: PostCss helps us compile CSS next code;
(3) Can Webpack handle CSS? How? Can Webpack handle CSS:
- Webpack itself is a JavaScript oriented modular packaging tool that can only handle JavaScript code.
- Webpack can handle CSS with the assistance of loader.
How to use Webpack to handle CSS:
- There are two key loaders used to operate the CSS in Webpack: csS-Loader and style-loader
- Note that saying “with what” may not be enough and the interviewer may wonder if you are memorising the answer, so you also need to know what each Loader does:
- Css-loader: imports the CSS module and compiles the CSS code.
- Style-loader: Creates a style tag to write CSS content to the tag.
In practice, CSS – Loaders must be executed before style-loaders. You can’t insert CSS code until the compilation process is complete; If you insert uncompiled code ahead of time, WebPack won’t understand the mess, and it will relentlessly report errors.
29. How can I tell if an element has reached the visible area
Take the picture display as an example:
window.innerHeight
Is the height of the browser viewable area;document.body.scrollTop || document.documentElement.scrollTop
Is the distance the browser has scrolled over;imgs.offsetTop
Is the height from the top of the element to the top of the document (including the distance of the scroll bar);- Content reaches the display area:
img.offsetTop < window.innerHeight + document.body.scrollTop;
30. Under what circumstances does the Z-index attribute become invalid
In general, z-index is used when there are two overlapping labels, with one of them appearing above or below the other under certain circumstances. The higher the z-index, the higher the upper level. The position attribute of the Z-index element should be relative, Absolute, or fixed.
The Z-index attribute is invalid in the following cases:
- When the position of the parent element is relative, the z-index of the child element is invalid. Fix: parent element position is absolute or static;
- The element does not set the position property to nonstatic. Fix: Set the element’s position to one of relative, Absolute, or fixed;
- The element sets the float float along with the z-index. Fix: float removed, display: inline-block;
31. What are the properties of CSS3’s transform
2. Page layout
1. Common CSS layout units
Common layout units include pixels (px), percentage (%), EM, REM, and VW /vh.
(1) Pixels (PX) are the basis of page layout. A pixel represents the smallest area that can be displayed on the screen of a terminal (computer, phone, tablet, etc.). There are two types of pixels: CSS pixels and physical pixels:
- CSS pixel: An abstract unit for Web developers to use in CSS;
- Physical pixels: The physical pixels of any device are fixed, depending only on the hardware density of the device.
(2) Percentage (%). When the width or height of the browser changes, the percentage unit can make the width and height of the components in the browser change with the change of the browser, so as to achieve a responsive effect. The percentage of child elements is generally considered relative to the immediate parent.
(3) Em and REM are more flexible than px. They are both units of relative length. The difference between them is that EM is relative to the parent element and REM is relative to the root element.
- Em: a unit of relative text length. The font size relative to the text in the current object. If the font size of the text in the current line has not been manually set, it is relative to the browser’s default font size (16px by default). A multiple of the font size of the parent element.
- Rem: REM is a new relative unit in CSS3 that is a multiple of the font-size of the root element (HTML element). What REM does: You can use REM to create simple, responsive layouts. You can use the ratio of the font size of HTML elements to the size of the screen to set the font size, so that the elements can change as the screen resolution changes.
(4) VW/Vh is a unit related to the view window. Vw represents the width of the view window, and Vh represents the height of the view window. In addition to VW and Vh, there are two related units, vmin and vmax.
- Vw: The window width is 100vw relative to the window width;
- Vh: The window height is 100vh relative to the window height;
- Vmin: smaller value in vw and Vh;
- Vmax: the larger value in vw and Vh;
Vw/VH is very similar to percentage, the difference is:
- The percentage (
%
) : Most elements are relative to their ancestors, but also relative to themselves (border-radius, translate, etc.) - Vw/VM: relative to window size
2. The differences between PX, EM and REM and the use scenarios
The difference between the three:
- Px is a fixed number of pixels, and once set it cannot be changed to fit the page size.
- Em and REM are more flexible than PX. They are units of relative length, which are not fixed in length, and are more suitable for responsive layouts.
- Em sets the font size relative to its parent element, which creates a problem. Setting any element may require knowing the size of its parent element. Rem is relative to the root element, which means that only one reference value needs to be determined at the root element.
Usage scenario:
- For those that only need to be adapted to a small number of mobile devices and the resolution has little impact on the page, use PX.
- For devices that need to be adapted to various mobile devices, such as iPhone and iPad, rem is used.
3. Implementation of the two-column layout
Generally, the two-column layout refers to the fixed width of the left column and the adaptive width of the right column. The concrete implementation of the two-column layout:
- Using float, set the width of the left element to 200px and float to the left. Set the margin-left of the right element to 200px and the width to auto (default is Auto to fill the entire parent element).
.outer {
height: 100px;
}
.left {
float: left;
width: 200px;
background: tomato;
}
.right {
margin-left: 200px;
width: auto;
background: gold;
}
Copy the code
- Using float, the left element is set to a fixed size and floats left, and the right element is set to overflow: hidden; This triggers the BFC on the right, and the region of the BFC does not overlap with the floating element, so there is no overlap on either side.
.left{
width: 100px;
height: 200px;
background: red;
float: left;
}
.right{
height: 300px;
background: blue;
overflow: hidden;
}
Copy the code
- Using the Flex layout, set the left element to a fixed width of 200px and the right element to Flex :1.
.outer {
display: flex;
height: 100px;
}
.left {
width: 200px;
background: tomato;
}
.right {
flex: 1;
background: gold;
}
Copy the code
- With absolute positioning, the parent element is set to relative positioning. The left element is set to absolute positioning and the width is set to 200px. Set the margin-left value of the right element to 200px.
.outer {
position: relative;
height: 100px;
}
.left {
position: absolute;
width: 200px;
height: 100px;
background: tomato;
}
.right {
margin-left: 200px;
background: gold;
}
Copy the code
- With absolute positioning, the parent element is set to relative positioning. Set the left element width to 200px, the right element to absolute positioning, the left element to 200px, and the rest of the orientation to 0.
.outer {
position: relative;
height: 100px;
}
.left {
width: 200px;
background: tomato;
}
.right {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 200px;
background: gold;
}
Copy the code
4. Implementation of the three-column layout
Three-column layout generally refers to a page with a total of three columns, the left and right columns of fixed width, the middle of the adaptive layout, the specific implementation of the three-column layout:
- Using absolute positioning, set the left and right columns as absolute positioning, and set the value of margin corresponding to the size of the direction in the middle.
.outer {
position: relative;
height: 100px;
}
.left {
position: absolute;
width: 100px;
height: 100px;
background: tomato;
}
.right {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 100px;
background: gold;
}
.center {
margin-left: 100px;
margin-right: 200px;
height: 100px;
background: lightgreen;
}
Copy the code
- Using a Flex layout, set the left and right columns to a fixed size and the middle column to Flex :1.
.outer {
display: flex;
height: 100px;
}
.left {
width: 100px;
background: tomato;
}
.right {
width: 100px;
background: gold;
}
.center {
flex: 1;
background: lightgreen;
}
Copy the code
- Using float, set the left and right columns to a fixed size and set the corresponding direction float. The middle column sets the left and right margin values. Note that this way, the middle column must be placed last: **
.outer {
height: 100px;
}
.left {
float: left;
width: 100px;
height: 100px;
background: tomato;
}
.right {
float: right;
width: 200px;
height: 100px;
background: gold;
}
.center {
height: 100px;
margin-left: 100px;
margin-right: 200px;
background: lightgreen;
}
Copy the code
- Grail layout, using float and negative margins to achieve. The parent element is set to the left and right padding, and the three columns are set to float left. The middle column is placed first, and the width is set to the width of the parent element, so the last two columns are pushed to the next row. Set the negative value of margin to move them to the previous row, and then use relative positioning to position both sides.
.outer {
height: 100px;
padding-left: 100px;
padding-right: 200px;
}
.left {
position: relative;
left: -100px;
float: left;
margin-left: -100%;
width: 100px;
height: 100px;
background: tomato;
}
.right {
position: relative;
left: 200px;
float: right;
margin-left: -200px;
width: 200px;
height: 100px;
background: gold;
}
.center {
float: left;
width: 100%;
height: 100px;
background: lightgreen;
}
Copy the code
- In the Dual wing layout, the left and right positions are reserved by the margin value of the middle column, rather than by the padding of the parent element, relative to the Holy Grail layout. Essentially, this is done by floating and negative margins.
.outer {
height: 100px;
}
.left {
float: left;
margin-left: -100%;
width: 100px;
height: 100px;
background: tomato;
}
.right {
float: left;
margin-left: -200px;
width: 200px;
height: 100px;
background: gold;
}
.wrapper {
float: left;
width: 100%;
height: 100px;
background: lightgreen;
}
.center {
margin-left: 100px;
margin-right: 200px;
height: 100px;
}
Copy the code
5. Realization of horizontal and vertical centering
- To use absolute positioning, first position the upper left corner of the element to the center of the page by using top:50% and left:50%, and then translate to adjust the center point of the element to the center of the page. This approach needs to consider browser compatibility issues.
.parent { position: relative; }.child { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }Copy the code
- Using absolute positioning, set the values of all four directions to 0, and set margin to auto. Since the width and height are fixed, the corresponding direction is bisector, and the center in the horizontal and vertical directions can be realized. This method is applicable to the case where the box has width and height:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
Copy the code
- Using absolute positioning, first positioning the upper left corner of the element to the center of the page through top:50% and left:50%, and then adjusting the center point of the element to the center of the page through the negative margin. This method is suitable for the case where the width and height of the box are known
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /* half of its own height */
margin-left: -50px; /* Half of its width */
}
Copy the code
- Using flex layout, you can center the container vertically and horizontally using the align-items:center and insert-content: Center, and then its children can be centered vertically and horizontally. This method should consider the compatibility problem. This method is widely used in mobile terminal:
.parent {
display: flex;
justify-content:center;
align-items:center;
}
Copy the code
6. How to adapt the mobile terminal according to the design draft?
Mobile terminal adaptation has two main dimensions:
- Suitable for different pixel density, for different pixel density, use CSS media query, select different accuracy of the picture, to ensure that the picture will not distortion;
- For different screen sizes, because different screens have different logical pixel sizes, if you directly use PX as the development unit, the developed page can be displayed accurately on one phone, but will be distorted on another phone. In order to adapt to different screen sizes, the content of the design should be scaled back.
In order to make the page size adaptive, we can use rem, EM, VW, VH and other relative units.
7. Understanding Flex layout and its usage scenarios
Flex, short for FlexibleBox, means “flexible layout” and is used to provide maximum flexibility for box-shaped models. Any container can be specified as a Flex layout. Inline elements can also be laid out using Flex. Note that when set to a Flex layout, float, clear, and vertical-align properties of child elements are invalidated. Elements that use a Flex layout are called Flex Containers, or “containers” for short. All of its child elements automatically become members of the container and are called Flex items, or “projects” for short. By default, a container has two axes: a horizontal main axis and a vertical cross axis. Items are arranged along the horizontal axis by default.
The following six properties are set on the container:
- The flex-direction attribute determines the direction of the spindle (that is, the alignment of the items).
- The flex-wrap property defines how to wrap lines if an axis does not fit.
- The flex-flow property is shorthand for the Flex-direction and flex-wrap properties, and defaults to Row nowrap.
- The inter-content attribute defines the alignment of items on the spindle.
- The align-items property defines how items are aligned on cross axes.
- The align-content attribute defines the alignment of multiple axes. This property does not work if the project has only one axis.
The following six properties are set on the project:
- The order attribute defines the order in which items are arranged. The smaller the value, the higher the order, the default is 0.
- The flex-grow property defines the magnification ratio of the project, which defaults to 0, meaning that if there is room left, it will not be enlarged.
- The Flex-shrink property defines the project shrink scale, which defaults to 1, meaning that the project will shrink if there is not enough space.
- The Flex-basis property defines the main space that the project occupies before allocating excess space. The browser uses this property to calculate whether the main axis has extra space. Its default value is Auto, which is the original size of the project.
- The Flex property is short for flex-grow, flex-shrink, and Flex-basis, and defaults to 0, 1 auto.
- The align-self property allows individual items to have a different alignment than other items, overriding the align-items property. The default value is Auto, which means that the align-items property of the parent element is inherited, and is equivalent to stretch if there is no parent element.
In simple terms: Flex layout is a new layout added to CSS3. You can make an element a Flex container by setting its display attribute to flex, and all of its children become its projects. By default, a container has two axes: a horizontal axis and a cross axis perpendicular to the axis. You can use flex-direction to specify the direction of the principal axis. You can use annotation-content to specify how elements will be arranged on the main axis, and align-items to specify how elements will be arranged on the cross axis. You can also use flex-wrap to specify how to wrap lines when there are no more than one line. For items in a container, you can use the Order attribute to specify the order in which items are arranged, you can also use flex-grow to specify the scale by which items will be enlarged when there is no room left, and you can use Flex-shrink to specify the scale by which items will be shrunk when there is no room left.
8. Concept and basic principles of responsive design
Responsive Web design is the ability for a website to be compatible with multiple terminals, rather than making a specific version for each terminal.
About the principle: the basic principle is through the media query (@media) query detection of different device screen size to do processing. About compatibility: The page header must have a viewport declared by mate.
<meta name="" viewport" " content="Width =" device - width," initial-scale="1." maximum-scale="1, user - scalable = no" "/>
Copy the code
Three, positioning and floating
1. Why do you need to clear floats? Clearing float mode
Definition of float: non-Ie browser, the container is not set height and child elements float, the container height can not be supported by the content. At this point, content spills out of the container and affects the layout. This phenomenon is called float (overflow).
How floating works:
- Floating elements break out of the document flow and do not occupy space (causing “height collapse” phenomenon)
- A floating element touches a border that contains it or another floating element
A floating element can be moved left and right until it encounters another floating element or an inclusion box on its outer edge. Floating boxes are not part of the normal flow in the document flow. After floating elements, the layout of block-level elements is not affected, only the layout of inline elements is affected. The normal flow in the document flow will then behave as if the float box does not have the same layout pattern. Height collapse occurs when the height of the containing box is less than that of the floating box.
Problems caused by floating elements?
- The height of a parent element cannot be stretched, affecting elements of the parent’s level
- Non-floating elements of the same class as the floating element will follow
- If the floating element is not the first element, then the elements before that element must also float, otherwise the display structure of the page will be affected
You can clear the float as follows:
- Define for the parent div
height
attribute - Add an empty div tag after the last floating element, and add
clear:both
style - Contains the floating element’s parent tag addition
overflow:hidden
oroverflow:auto
- Use the :after pseudo-element. Since IE6-7 does not support :after, use Zoom :1 to trigger hasLayout**
.clearfix:after{
content: "\200B";
display: table;
height: 0;
clear: both;
}
.clearfix{
*zoom: 1;
}
Copy the code
2. How does the clear property clear the float?
Use the clear property to clear the float. The syntax is as follows:
clear:none|left|right|both
Copy the code
If taken literally, “clear:left” means “clear left float” and “clear:right” means “clear right float”. In fact, this interpretation is problematic because the float is still there and has not been cleared.
“The edge of the element box should not be adjacent to the floating element.” The clear attribute is set on the element to avoid the impact of the floating element, not to clear the floating element.
Note also that the clear property means that the edge of the element box must not be adjacent to the preceding floating element. Note that the “preceding” three words in this case, that is, the clear property does not care about the “following” floating element. Given that the float property is either left or right, it cannot exist at the same time, and since the clear property does not care about the “next” floating element, when clear:left is valid, clear:right must be invalid. Clear :left = clear:both; Similarly, clear:right if valid is the same as setting clear:both. Thus, clear:left and clear:right these two statements do not have any use value, at least in the CSS world, directly use clear:both.
To clear a float, use pseudo-elements:
.clear::after{ content:' '; display: block; clear:both; }Copy the code
The clear property is valid only for block-level elements, whereas pseudo-elements such as ::after are inline horizontal by default, which is why you need to set the display property value when using pseudo-elements to clear floating effects.
3. Understanding the BFC and how to create a BFC
Let’s start with two related concepts:
- Box: The Box is the object and basic unit of CSS layout. A page is made up of many boxes. This Box is called the Box model.
- Block-level context is a rendering area of the page, with a set of rendering rules that determine how its children are positioned, and how they relate to and interact with other elements.
Block Formatting Context (BFC) is part of the visual CSS rendering of Web pages. It is the area where block-level boxes are generated during the layout process, and where floating elements interact with other elements.
Generally speaking: BFC is an independent layout environment, which can be understood as a container. In this container, items are placed according to certain rules without affecting the items in other environments. If an element meets the conditions that trigger the BFC, the layout of the elements in the BFC is unaffected by external influences.
Conditions for creating a BFC:
- Root element: body;
- Element set float: float values other than none;
- The element sets absolute positioning: position (absolute, fixed);
- Display values: inline-block, table-cell, table-caption, flex, etc.
- The overflow value is hidden, auto, scroll;
BFC features:
- Vertically, from top to bottom, the same way the document flow is arranged.
- Margins of two adjacent containers in the BFC overlap
- When calculating the height of the BFC, you need to calculate the height of the floating element
- The BFC region does not overlap with the floating container
- The BFC is a separate container, and elements inside the container do not affect external elements
- The left margin of each element touches the left border of the container
Role of BFC:
- Solve the overlapping problem of Margin: Since BFC is an independent area, internal elements and external elements do not affect each other, the two elements are changed into two BFC, and the overlapping problem of margin is solved.
- Solve the problem of height collapseAfter the child element is set to float, the parent element will collapse in height, that is, the parent element’s height will become 0. To solve this problem, simply change the parent element into a BFC. A common approach is to set the parent element
overflow:hidden
. - Create an adaptive two-column layout: This can be used to create an adaptive two-column layout with a fixed width on the left and an adaptive width on the right.
.left{
width: 100px;
height: 200px;
background: red;
float: left;
}
.right{
height: 300px;
background: blue;
overflow: hidden;
}
<div class="left"> < /div>
<div class="right"> < /div>
Copy the code
Set float:left on the left and overflow: hidden on the right. This triggers the BFC on the right, and the area of the BFC does not overlap with the floating elements, so the two sides do not overlap, achieving an adaptive two-column layout.
4. What is margin overlap? How to solve it?
The upper and lower margins of two block-level elements may be merged (collapsed) into a single margin, and the size of the larger margin is taken. This behavior is called margin folding. It is important to note that the margins of floating elements and absolutely positioned elements outside the document flow do not collapse. Overlap only occurs in the vertical direction.
Calculation principle: The calculation principle of margin after folding and merging is as follows:
- If both are positive, go for the largest
- If it’s a plus and a minus, it’s going to be the positive minus the absolute value of the negative
- When both of them are negative, you subtract 0 from the one with the largest absolute value
Solution: For folding cases, there are two main types: overlap between brothers and overlap between father and son (1) overlap between brothers
- The bottom element becomes an in-line box:
display: inline-block
- The bottom element sets the float:
float
- The value of position for the bottom element is
absolute/fixed
(2) Overlap between father and son
- Parent element added:
overflow: hidden
- Parent element to add transparent border:
border:1px solid transparent
- Child elements become inline boxes:
display: inline-block
- Child elements are added with a float attribute or positioning
5. The cascading order of elements
Stacking order, known as stacking order, means that there is a particular vertical display order in which elements are stacked. Here are the cascading rules for the box model:In the figure above, from top to bottom are: (1) Background and border: The background and border that create the current cascading context element. (2) negative z-index: The element whose z-index attribute value is negative in the current cascading context. (3) Block-level box: non-in-line level non-location descendant elements in the document stream. (4) Floating box: non-positioning floating element. (5) In-line box: in-line level non-located descendant elements in the document stream. (6) Z-index :0: positioning elements whose cascading series is 0. (7) Positive Z-index: the value of z-index attribute is a positive positioning element.
Note: When locating the element Z-index :auto, the generation box’s level in the current context is 0, and no new context is created, except for the root element.
6. What are the attributes of position and what are the differences
Position has the following attribute values:
Attribute values | An overview of the |
---|---|
absolute | An element that generates absolute positioning, positioned relative to a parent element other than static positioning. The position of the element is specified by the left, top, right, and bottom attributes. |
relative | Generates an element that is positioned relative to its original position. The position of the element is specified by the left, top, right, and bottom attributes. |
fixed | Generates an absolutely positioned element, specifying the element position by specifying its position relative to the screen viewport. The positions of elements do not change as the screen scrolls, such as the back to the top button. |
static | By default, elements appear in normal document flow without positioning, ignoring top, bottom, left, right, or Z-index declarations. Block-level elements are arranged vertically from top down, and row-level elements from left to right. |
inherit | Specifies the value of the position attribute inherited from the parent element |
The positioning methods of the first three are as follows:
- Relative: The positioning of an element is always relative to its own position, and does not affect other elements.
- Fixed: Elements are positioned relative to the window (or iframe) boundary, regardless of other elements. But it can be destructive, causing other elements to change positions.
- Absolute:Element positioning is a lot more complicated than the first two. If top and left are set for absolute, how does the browser determine the vertical and landscape offsets? The answer is that the browser will recursively look for all the parent elements of that element, if it finds a setting
position:relative/absolute/fixed
If it is not found, it is located at the browser boundary. As shown in the following two figures:
7. Relationship between display, float, and position
(1) First determine whether the display attribute is none. If it is none, then the values of position and float do not affect the final performance of the element.
(2) Then determine whether the value of position is absolute or fixed. If yes, the float property is invalid, and the value of display should be set to table or block. The specific conversion needs to see the initial conversion value.
(3) If the value of position is not Absolute or fixed, determine whether float is none. If not, then the value of display is converted as above. Note that if the value of position is relative and the value of float is present, relative is positioned relative to the final position after the float.
(4) If float is none, then determine whether the element is the root element. If it is the root element, then the display attribute is converted according to the above rules. If not, then the specified display attribute value is left unchanged.
In general, think of it as a priorite-like mechanism, with “position: Absolute “and “position:fixed” having the highest priority. While it’s there, float doesn’t work, and the value of ‘display’ needs to be adjusted. Second, adjust the value of ‘display’ if the element’s ‘float’ property is not “None” or if it is the root element; Finally, for elements that are not root, and are not floating, and are not absolutely positioned, the value of the ‘display’ property is the same as the set value.
8. The common and different points are absolute and fixed
Thing in common:
- Change the rendering of inline elements to inline-block
- Removes elements from the normal document flow and no longer occupies physical space in the document
- Overrides non-located document elements
Difference:
- Abuselute is different from the root element of fixed, which can be set; fixed is the browser.
- In pages with scrollbars, Absolute will follow the parent element to move, fixed fixed in the specific location of the page.
9. Understanding of sticky location
If someone is sticky, he or she is sticky. Grammar: position: sticky; Location based on the user’s scrolling position.
The element of sticky positioning depends on the user’s scrolling, switching between position:relative and position:fixed. It behaves like position:relative; When the page scrolls beyond the target area, it behaves like position:fixed; , it will be fixed in the target position. Element positioning is represented by relative positioning until a certain threshold is crossed, and then by fixed positioning. This particular threshold refers to one of the top, right, bottom, or left thresholds, in other words, specify one of the top, right, bottom, or left thresholds for sticky positioning to take effect. Otherwise it behaves the same as relative positioning.
Iv. Scenario Application
1. Implement a triangle
CSS draws triangles using the border attribute, which is the border.
At ordinary times, when setting the border to the box, it is often set very narrow, and it may be mistaken that the border is composed of a rectangle. In fact, the border attribute is made up of the right triangle. Here’s an example:
div {
width: 0;
height: 0;
border: 100px solid;
border-color: orange blue red green;
}
Copy the code
Setting the length and width of the element to 0 gives the following effect:So we can draw a triangle based on the border feature:(1) Triangle 1
div { width: 0; height: 0; border-top: 50px solid red; border-right: 50px solid transparent; border-left: 50pxsolid transparent; }Copy the code
(2) Triangle 2
div {
width: 0;
height: 0;
border-bottom: 50px solid red;
border-right: 50px solid transparent;
border-left: 50px solid transparent;
}
Copy the code
(3) Triangle 3
div {
width: 0;
height: 0;
border-left: 50px solid red;
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
}
Copy the code
(4) Triangle 4
div {
width: 0;
height: 0;
border-right: 50px solid red;
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
}
Copy the code
(5) Triangle 5
div {
width: 0;
height: 0;
border-top: 100px solid red;
border-right: 100px solid transparent;
}
Copy the code
There are many, not a realization, the general principle is to control the direction of the triangle through the upper and lower left and right border, with the width ratio of the border to control the Angle of the triangle.
2. Implement a fan
Using CSS to achieve the idea of fan and triangle is basically the same, is more than a rounded style, to achieve a 90° fan:
div{
border: 100px solid transparent;
width: 0;
heigt: 0;
border-radius: 100px;
border-top-color: red;
}
Copy the code
3. Implement an adaptive width and height square
- Using VW to achieve:
.square {
width: 10%;
height: 10vw;
background: tomato;
}
Copy the code
- Using the property that the margin/padding percentage of the element is relative to the parent element width:
.square {
width: 20%;
height: 0;
padding-top: 20%;
background: orange;
}
Copy the code
- Use the margin-top value of the child element to achieve:
.square {
width: 30%;
overflow: hidden;
background: yellow;
}
.square::after {
content: ' ';
display: block;
margin-top: 100%;
}
Copy the code
4. Draw a 0.5px line
- The transform: scale() method is used to define the 2D scale of the element:
transform: scale(0.5.0.5);
Copy the code
- Use the meta viewport method
<meta name="viewport" content="width=device-width.initial-scale=0.5, minimum-scale=0.5, maximum-scale=0.5"/ >Copy the code
This will scale it by a factor of 0.5, and if it’s 1px it will be 0.5px. Viewport only works on mobile, so you can only see it on mobile
5. Set a font less than 12px
In Google’s CSS set font size to 12px or less, the display size is the same, which is 12px by default.
The solution:
- -webkit-text-size adjust:none; -webkit-text-size :none; The font size is unlimited. However, chrome will not be available after the update to version 27. The -webkit-text-size-Adjust style is no longer supported on higher versions of Chrome, so use it with caution.
- Webkit-transform :scale(0.5); webkit-transform:scale(0.5); Note – its – transform: scale (0.75); Display: block/inline-block/… Display: block/inline-block/… ;
- Use images: If the content is fixed, use the text less than 12px to cut out the image, this does not affect compatibility and aesthetics.
How to solve the 1px problem?
The 1px issue refers to the fact that on some Retina models, the 1px of a mobile page will become thicker and look more than 1px. The reason is simple — 1px in CSS is not the same as 1px on a mobile device. The ratio between them has a special property to describe:
Windows. devicePixelRatio = Device physical pixels/CSS pixels.Copy the code
Open Chrome, start mobile debug mode, and output this in the consoledevicePixelRatio
The value of the. Select iphone6/7/8, the output is 2:This means that a CSS pixel of 1px is actually rendered with 2 physical pixel units on this device, so it must look a little thicker than 1px.There are three ways to solve the 1px problem:
Idea 1: Write 0.5px directly
If the previous 1px style was written like this:
border:1px solid # 333
Copy the code
DevicePixelRatio = windows.devicepixelratio = windows.devicepixelratio = windows.devicepixelratio = windows.devicepixelratio = windows.devicepixelratio = windows.devicepixelratio = windows.devicepixelratio = windows.devicepixelRatio = windows.devicepixelRatio = windows.devicepixelRatio = windows.devicepixelRatio = windows.devicepixelRatio = windows.devicepixelRatio
<div id="container" data-device={{window.devicePixelRatio}}></div>
Copy the code
You can then use a property selector in your CSS to match a devicePixelRatio of 2, such as here:
#container[data-device="2"] {
border:0.5 px. solid # 333
}
Copy the code
Changing 1px to the value after the 1/devicePixelRatio is by far the easiest way to do this. The downside of this approach is that it is not compatible. IOS requires versions 8 and above, while Android is not compatible.
Idea two: pseudo-elements first zoom in and then zoom out
This approach is more feasible and more compatible. The only downside is that it gets more code.
The idea is to add a ::after pseudo-element to the target element, make the layout of the element absolute, spread the entire target element, and then set its width and height to twice the target element, and the border value to 1px. Then with the help of the CSS animation effects in the shrink ability, the entire pseudo-element is reduced to 50% of the original. At this time, the width and height of the pseudo-element can be aligned with the original target element, and the border is also reduced to one half of 1px, indirectly achieving the effect of 0.5px.
The code is as follows:
#container[data-device="2"] {
position: relative;
}
#container[data-device="2"]::after{
position:absolute;
top: 0;
left: 0;
width: 200%;
height: 200%;
content:"";
transform: scale(0.5);
transform-origin: left top;
box-sizing: border-box;
border: 1px solid # 333; }}Copy the code
Idea 3: Viewport scaling to solve
The idea is to start with a few key attributes in the meta tag:
<meta name="viewport" content="Initial - scale = 0.5, the maximum - scale = 0.5, the minimum - scale = 0.5, user - scalable = no">
Copy the code
Here, for a page with a pixel ratio of 2, the entire page is scaled to 1/2 of its original size. Thus, a 1px style that used to take up 2 physical pixels now takes up the standard 1 physical pixel. Depending on the pixel ratio, this scaling can be calculated to a different value, using the js code as follows:
const scale = 1 / window.devicePixelRatio;
MetaEl refers to the Dom corresponding to meta tags
metaEl.setAttribute('content'.`width=device-width,user-scalable=no,initial-scale=${scale},maximum-scale=${scale},minimum-scale=${scale}`);
Copy the code
That worked, but it also had the side effect of making the entire page zoom. At this point 1px has been processed to the physical pixel size, which is a good size for displaying borders on a phone. However, some content that does not need to be narrowed, such as text, pictures and so on, is also narrowed without distinction.