CSS-HTML Knowledge Points and Analysis of High-frequency Exam Questions

Knowledge point combing

  • Selector weights and priorities

  • box model

    • box size calculation
    • Overlap calculation of margin
  • float

    float
    
    • Floating Layout Concept
    • cleanup float
  • position

    position
    
    • document flow concept
    • Location classification
    • fixed targeting features
    • Absolute positioning calculation method
  • flexlayout

  • How to achieve center alignment?

  • understand semantics

  • CSS3 animation

  • repaint and reflow


Selector weights and priorities

There are many CSS selectors, and different selectors have different weights and priorities. For an element, if there are multiple selectors, then its priority needs to be calculated according to the weight.

The weights are divided into four levels, namely:

  1. Represents an inline style, for example style="xxx", the weight is 1000;
  2. Represents the ID selector, for example #content, the weight is 100;
  3. Represents classes, pseudo-classes and attribute selectors, such as .content, :hover, [attribute], with a weight of 10;
  4. Represents element selectors and pseudo-element selectors, such as div, p, with a weight of 1.

It should be noted that general selectors (*), child selectors (>) and adjacent sibling selectors (+) are not in these four levels, so their weights are all 0 . A selector with a large weight value also has a high priority, and the priority of the same weight follows the latter definition and overrides the previous definition.

box model

what is a "box"

padding borderFriends who are beginners in CSS must have learned and when they first learned the basics of CSS margin, that is, inner margin, border and outer margin. The three of them constitute a "box". Just like the express delivery we received, we originally bought a small mobile phone, but what we received was such a big box. Because there is a spacer (inner margin) between the white packaging box of the mobile phone and the mobile phone machine, the white box of the mobile phone has a thickness, although it is very thin (the border), and there is a layer of foam board (the outer margin) between the box and the express box. This is a typical box.

insert image description here

As shown in the picture above, the real content is these texts. There is a 10px inner margin around the text, a 5px border, and a 10px outer margin. See the box?

Topic: How to calculate the width of the box model

fixed width box

<div style="padding:10px; border:5px solid blue; margin: 10px; width:300px;">
    之前看过一篇文章,叫做《浏览器工作原理:新式网络浏览器幕后揭秘》,
    文章言简意赅的介绍的浏览器的工作过程,web前端
</div>

insert image description here

As shown in the picture above, after getting the effect of the web page, we can use the screenshot tool to measure the width of the text content. It is found that the width of the text content is exactly 300px, which is the width we set.

Therefore, in the box model, the width we set is the content width, not the width of the entire box. And the width of the entire box is: the sum of (content width + borderwidth + paddingwidth +margin width) . In this way, if we change one of the four, it will cause the width of the box to change. It's not kind to us.

It doesn't matter, this thing is not friendly, someone has discovered it a long time ago, and it has been resolved, and I will talk about it later.

box that fills the parent container

By default, divyes display:block, the width will fill the entire parent container. As shown below:

<div style="padding:10px; border:5px solid blue; margin: 10px; width:300px;">
    之前看过一篇文章,叫做《浏览器工作原理:新式网络浏览器幕后揭秘》,
    文章言简意赅的介绍的浏览器的工作过程,web前端
    之前看过一篇文章,叫做《浏览器工作原理:新式网络浏览器幕后揭秘》,
    文章言简意赅的介绍的浏览器的工作过程,web前端
</div>

insert image description here

But don't forget, this div is a box model, its entire width includes (content width + borderwidth + paddingwidth + marginwidth), and the entire width fills the parent container.

That's the problem. If the width of the parent container remains the same, if we manually increase marginor the width value of one of them, the width of the content will decrease. In extreme cases, if the width of the content is compressed to the point that it cannot be compressed any more (for example, the width of a word), then the browser will force the width of the parent container to increase. This is not what we want to see.borderpadding

box that wraps the contents

paddingThis case is relatively simple, the width of the content is calculated according to the content, and the width of the box will be added to the sum of ( width + borderwidth + marginwidth) on the basis of the content width .

<div style="padding:10px; border:5px solid blue; margin: 10px; width:300px;">
    之前看过一篇文章,叫做《浏览器工作原理:新式网络浏览器幕后揭秘》
</div>

insert image description here

box-sizing:border-box

As mentioned earlier, setting the width for the box model results in only setting the width of the content, which is unreasonable. How to solve this problem? The answer is to style the box: box-sizing:border-box.

<div style="padding:10px; border:5px solid blue; margin: 10px; width:300px; box-sizing:border-box;">
    之前看过一篇文章,叫做《浏览器工作原理:新式网络浏览器幕后揭秘》
</div>

insert image description here

In the picture above, after divsetting box-sizing:border-box, the width of 300px is the content + padding+ the width of the border (not included margin) , which is more in line with our actual requirements. It is recommended that when you write CSS for the system, the first style is:

* {
    box-sizing:border-box;
}

The famous Bootstrap also adds box-sizing:border-boxit to its *selector, why don't we do it?

Vertical margin overlap

When we mention margin here, we have to mention this feature of margin—vertical overlap. If <p>the vertical margin is 16px, <p>what is the vertical distance between the two? —— According to common sense, it should be 16 + 16 = 32px, but the answer is still 16px. Because the vertical margins will overlap, if the two are not the same size, the larger one will "eat" the smaller one.


floatfloat

Float is often used for web page layout, and it is relatively simple to use. Here are some important knowledge points that need attention for your reference.

misunderstanding and misuse

float was originally designed to be used for text wrapping effects , that is, a picture and a text, float:leftafter the picture, the text will wrap around the picture.

<div>
    <img src="image/1.png" style="float:left">
    一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字一段文字
</div>

However, later everyone found that the combination float + divcan achieve tablethe web page layout that was previously implemented, so it was "misused" for the web page layout.

Topic: Why does float cause the parent element to collapse?

destructive

insert image description here

The destructiveness of float - float destroys the original structure of the parent tag, causing the parent tag to collapse. The most fundamental reason for this phenomenon is that elements set with float will break away from the document flow . The fundamental reason is that float was originally designed to solve the problem of text wrapping around pictures. Everyone should remember this effect of float.

Packaged

Encapsulation is also a very important feature of float, and everyone must be familiar with this feature when using float. Let's start with a small example:

insert image description here

As shown in the figure above, if a normal div does not have a width set, it will fill the entire screen, as mentioned in the previous box model section. And if the div is added float:left, it suddenly becomes compact, the width changes, and the three words in the content are wrapped—this is the wrapping property. After setting float for the div, its width will be automatically adjusted to wrap the width of the content instead of filling the entire parent container.

Note that although the div reflects the wrapping at this time, its display style has not changed, still display: block.

Why should float be wrapped? In fact, the answer still has to be found from the original design intention of float. Float is designed to achieve text wrapping effect. It's easy to understand that text wraps around pictures, but what if you want text to wrap around a div? At this time, if the div is not "wrapped", the wrapping effect cannot be achieved.

clear space

float also has a feature that you may not be very familiar with-clear spaces. As usual, let's give an example first.

<div style="border: 2px solid blue; padding:3px;">
    <img src="image/1.png"/>
    <img src="image/2.png"/>
    <img src="image/3.png"/>
    <img src="image/4.png"/>
</div>

insert image description here

After adding float:left:

insert image description here

In the first picture above, there will be spaces in the middle of the normal img, because multiple img tags will have line breaks, and the browser recognizes line breaks as spaces, which is also normal. In the second picture, float:leftthe style added to the img makes there are no spaces between the imgs, and the 4 imgs are next to each other.

If you didn't pay attention before, now think about whether the programs you wrote before have this feature. Why is float suitable for web page layout (commonly known as "bricklaying")? It is because the webpage typesetting by float fits perfectly, and even a fly cannot fly in the middle.

The root cause of the "clear spaces" feature is that floats cause nodes to fall out of the document flow structure. It does not belong to the document flow structure, so the newlines and spaces around it have nothing to do with it, and it tries to move as close as possible to one side, which is the essence of clearing spaces.

Title: Handwritten clearfix

clearfix

To clear the effect of floating, the generally used styles are as follows, which are collectively referred to clearfixas codes. The parent container of all float elements should generally add clearfixthis class.

.clearfix:after {
    content: '';
    display: table;
    clear: both;
}
.clearfix {
    *zoom: 1; /* 兼容 IE 低版本 */
}
<div class="clearfix">
    <img src="image/1.png" style="float: left"/>
    <img src="image/2.png" style="float: left"/>
</div>

summary

The original design of float is to solve the problem of text wrapping pictures, and later it was used for layout by mistake, so there are many inappropriate or need to pay attention to, the above basically mentioned the required knowledge points. If you are a student who is new to float, after learning the above basic knowledge, you should do some exercises for actual combat - the classic "holy grail layout" and "double flying wing layout". I won’t talk about it here. There are a lot of information on the Internet, such as the two classic layouts that are often tested in interviews-the Holy Grail and the Double Flying Wings (the last two pictures of this article clearly show these two layouts).


positionposition

position is used for the positioning of web page elements, and these values ​​can be set static/relative/absolute/fixed, among which static is the default value, no need to introduce.

Topic: What is the difference between relative and absolute?

relative

Relative positioning relative can be easily demonstrated with an example. For example, if we write 4 <p>, you can know what it looks like without looking at it.

<p>第一段文字</p>
<p>第二段文字</p>
<p>第三段文字</p>
<p>第四段文字</p>

insert image description here

<p>Then we add position:relativeand set leftthe sum value on the third one topto see <p>how this changes.

<p>第一段文字</p>
<p>第二段文字</p>
<p style="position:relative; top: 10px; left: 10px">第三段文字</p>
<p>第四段文字</p>

insert image description here

In the picture above, you should recognize two pieces of information (I believe most people will ignore the second piece of information)

  • The position of the third one <p>has changed, moving 10px to the right and down respectively;
  • It is also important to note that the other three <p>positions have not changed.

It can be seen that relative will cause relative changes in its own position without affecting the position and size of other elements . This is one of the points of relative. There is a second point, which is that relative generates a new positioning context. The following is a detailed introduction to the positioning context. Here, an example can be used to show the difference:

insert image description here

Pay attention to the difference between the two pictures, which will be explained below.

absolute

Or write a basic demo first.

<p>第一段文字</p>
<p>第二段文字</p>
<p style="background: yellow">第三段文字</p>
<p>第四段文字</p>

insert image description here

Then, we change the third <p>to position:absolute;, and see what happens.

insert image description here

From the above results, we can see several information:

  • The absolute element breaks away from the document structure. Unlike relative, the positions of the other three elements are rearranged. It can be destructive whenever an element would fall out of the document structure, causing the parent element to collapse. (As you should immediately recall at this point, float elements also break out of the document structure.)
  • The absolute element is "wrapping". The previous <p>width was to fill the entire screen, but <p>the width at this time is just the width of the content.
  • The absolute element has "following". Although the absolute element is out of the document structure, its position has not changed, and it still stays in its original position honestly, because we have not set the top and left values ​​at this time.
  • The absolute element will float above the page and will block the content of the page below.

Finally, by setting the top and left values ​​for the absolute element, you can customize its content, which is usually more commonly used. It should be noted here that when the top and left values ​​are set, the element is positioned relative to the nearest positioning context, not relative to the browser.

fixed

In fact, fixed and absolute are the same, the only difference is: the absolute element determines the position according to the nearest positioning context, while the fixed determines the position according to the window (or iframe).

Topic: Who are relative, absolute and fixed based on?

positioning context

The positioning of relative elements is always relative to the position of the element itself, and has nothing to do with other elements, nor will it affect other elements.

insert image description here

The positioning of the fixed element is relative to the window (or iframe) boundary, and has nothing to do with other elements. But it's destructive and causes changes in the position of other elements.

insert image description here

The positioning of absolute is much more complicated than the first two. If top and left are set for absolute, what will the browser use to determine its vertical and horizontal offsets? The answer is that the browser will recursively search for all parent elements of the element. If it finds an position:relative/absolute/fixedelement that is set, it will be positioned based on the element. If it is not found, it will be positioned based on the browser boundary. As shown in the following two figures:

insert image description here

insert image description here


flexlayout

Traditional solutions for layouts are based on the box model, dependency displayproperty + positionproperty + floatproperty. It is very inconvenient for those special layouts, for example, vertical centering (explained below) is not easy to achieve. In the current mainstream mobile pages, the use of flex layout can better meet the requirements, so the knowledge of flex layout must be mastered.

basic use

Any container can use flex layout, and the code is very simple.

<style type="text/css">
    .container {
      display: flex;
    }
    .item {
        border: 1px solid #000;
        flex: 1;
    }
</style>

<div class="container">
    <div class="item">aaa</div>
    <div class="item" style="flex: 2">bbb</div>
    <div class="item">ccc</div>
    <div class="item">ddd</div>
</div>

insert image description here

Note that the third one <div>, the flex: 2others , so that the second one is twice as wide as the others .<div>flex: 1<div><div>

design principle

The set display: flexelement is called "container" (flex container), and all its child nodes are called "members" (flex item). The container has two axes by default: the horizontal main axis and the vertical cross axis. The starting position of the main axis (the intersection with the border) is called main start, and the ending position is called main end; the starting position of the cross axis is called cross start, and the ending position is called cross end. Items are arranged along the main axis by default. The main axis space occupied by a single item is called main size, and the cross axis space occupied by a single item is called cross size.

insert image description here

Combine the above text and pictures, and read it again in detail, so that you can understand the design principle of flex and use it better.

Set the direction of the main axis

flex-directionCan determine the direction of the main axis, there are four optional values:

  • row (default): the main axis is horizontal, and the starting point is at the left end.
  • row-reverse: The main axis is horizontal, and the starting point is at the right end.
  • column: The main axis is vertical, and the starting point is the upper edge.
  • column-reverse: The main axis is vertical, and the starting point is at the bottom.
.box {
  flex-direction: column-reverse| column | row | row-reverse;
}

The axis direction set by the above code will correspond to the following figure in turn:

insert image description here

Sets the alignment of the main axis

justify-contentThe property defines the alignment of the item on the main axis, with the following values:

  • flex-start (default): Align to the start of the main axis.
  • flex-end: Align towards the end of the main axis.
  • center: centered.
  • space-between: Both ends are aligned, and the intervals between items are equal.
  • space-around: Equal spacing on both sides of each item. So, the spacing between items is twice as large as the spacing between items and the border.
.box {
    justify-content: flex-start | flex-end | center | space-between | space-around;
}

insert image description here

Alignment of the cross axis

align-itemsThe property defines how items are aligned on the cross axis, with the following values:

  • flex-start: The starting point of the cross axis is aligned.
  • flex-end: The end of the cross axis is aligned.
  • center: The midpoint of the cross axis is aligned.
  • baseline: The baseline alignment of the first line of text in the item.
  • stretch (default): If the item does not have a height set or is set to auto, it will take up the entire height of the container.
.box {
    align-items: flex-start | flex-end | center | baseline | stretch;
}

insert image description here


How to achieve center alignment?

Question: How to achieve horizontal centering?

center horizontally

Inline elements text-align: center;can be used, as follows:

.container {
   text-align: center;
}

The block element can be used margin: auto;, and many websites in the PC era do this.

.container {
    text-align: center; 
}
.item {
    width: 1000px;
    margin: auto; 
}

Absolutely positioned elements can be combined leftand marginimplemented, but the width must be known.

.container {
    position: relative;
    width: 500px;
}
.item {
    width: 300px;
    height: 100px;
    position: absolute;
    left: 50%;
    margin: -150px;
}

Topic: How to achieve vertical centering?

vertical center

line-heightThe value that can be set by the inline element is equal to heightthe value, such as a single line of text is vertically centered:

.container {
   height: 50px;
   line-height: 50px;
}

Absolutely positioned elements can be combined leftand marginimplemented, but the size must be known.

  • Advantages: good compatibility
  • Disadvantage: need to know the size in advance
.container {
    position: relative;
    height: 200px;
}
.item {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -20px;
    margin-left: -40px;
}

Absolute positioning can be combined transformto achieve centering.

  • Advantage: No need to know the size in advance
  • Disadvantages: poor compatibility
.container {
    position: relative;
    height: 200px;
}
.item {
    width: 80px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: blue;
}

Absolute positioning combination margin: auto, no need to know the size in advance, good compatibility.

.container {
    position: relative;
    height: 300px;
}
.item {
    width: 100px;
    height: 50px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

There are other solutions, but there is no need to master too much, just be able to name the solutions above.


understand semantics

Topic: How to understand HTML semantics?

The so-called "semantics" is to make it easier to understand, which is divided into two parts:

  • Make it easier for people (writing programs, reading programs) to understand
  • Make machines (browsers, search engines) more readable

make it easier to read

For humans, code readability and semantics are a very broad concept. For example, when defining JS variables, use more readable names, and when defining CSS classes, the same is true, such as etc., instead of using this kind length listof a bwho Can't understand the name.

However, the "semantics" we usually examine does not examine such broad and broad issues, but examines the semantics of HTML in order to better allow machines to understand HTML.

Make it easier for machines to understand

HTML conforms to the XML standard, but it is different from XML - HTML does not allow custom tag names like XML, and HTML has its own specified tag names. Here lies the problem—why does HTML specify so many tag names, such as p div h1 uletc.—for semantics. In fact, if you are proficient in CSS, you can use all <div>tags to achieve all web page effects, and p h1 ulyou can use none of the other tags. But we don't recommend doing this, because doing so will lose the meaning of HTML semantics.

Take a search engine as an example, the crawler downloads the HTML code of our webpage, how can it better understand the content of the webpage? —— It is the established label according to HTML. h1The label represents the title; pthe content inside is the detailed content of the paragraph, and the weight is definitely not as high as the title; the ulinside is a list; strongit is the bold and emphasized content... If we do not write according to HTML semantics and use <div>tags for everything, then the search engine It will be difficult to understand the content of our web pages.

In order to strengthen the semantics of HTML, the HTML5 standard has added header section articlesuch tags. Therefore, when writing HTML, semantics are very important, otherwise W3C would not have worked so hard to formulate these standards.


CSS3 animation

CSS3 can achieve animation, replacing the original Flash and JavaScript solutions.

First, use @keyframesthe definition of an animation named as testAnimationthe following code to set different CSS styles by percentage to specify the change of the animation. All animation changes can be defined in this way.

@keyframes testAnimation
{
    0%   {background: red; left:0; top:0;}
    25%  {background: yellow; left:200px; top:0;}
    50%  {background: blue; left:200px; top:200px;}
    75%  {background: green; left:0; top:200px;}
    100% {background: red; left:0; top:0;}
}

Then, animate a CSS selector, such as an divelement, as follows:

div {
    width: 100px;
    height: 50px;
    position: absolute;

    animation-name: myfirst;
    animation-duration: 5s;
}

animation-nameCorresponding to the name of the animation, animation-durationit is the duration of the animation, and there are other attributes:

  • animation-timing-function: Specifies the speed curve of the animation. default isease
  • animation-delay: Specifies when the animation starts. Default is 0
  • animation-iteration-count: Specifies the number of times the animation is played. Default is 1
  • animation-direction: Specifies whether the animation will play backwards in the next cycle. default isnormal
  • animation-play-state: Specifies whether the animation is running or paused. default isrunning
  • animation-fill-mode: Specify how to apply to the target of the animation before and after the animation is executed. The default is to nonekeep it in the last frame and it can be usedforwards

Topic: What's the difference between CSS's transitionand animation?

First of transitionall animation, both can be animated. From a semantic point of view, transitionit is a transition, from one state to another, such as the transition from height 100pxto 200px; animationbut animation, that is, more professional animation, animationwith the concept of frames, you can set the key Frames keyframe, an animation can consist of multiple keyframes and multiple state transitions, and also animationcontains multiple properties mentioned above.

repaint and reflow

Redrawing and reflow are frequently asked questions in interview questions, and they are also points that should be paid attention to in performance optimization. The author will briefly introduce them below.

  • Redrawing : refers to when the elements in the page do not break away from the document flow, but simply change the style, such as modifying the color, background, etc., the browser redraws the style
  • Reflow : refers to the situation where the browser re-renders part or all of the document when the size, position or certain properties of the DOM in the document flow change

In contrast, reflows are more expensive than redraws . In addition, the reading of some properties will also cause reflow, such as reading the height and width of a certain DOM, or using getComputedStylemethods. Avoid reflows and redraws when writing code. For example, the following questions may be encountered in the written test:

Topic: Find the optimization point of the following code and optimize it

var data = ['string1', 'string2', 'string3'];
for(var i = 0; i < data.length; i++){
    var dom = document.getElementById('list');
    dom.innerHTML += '<li>' + data[i] + '</li>';
}

The above code is acquired each time in the loop dom, and then accumulates the internal HTML li, and operates the DOM structure each time, which can be changed to use documentFragmentor traverse the strings that make up the HTML first, and operate once at the end innerHTML.


summary

Several properties mentioned above.

repaint and reflow

Redrawing and reflow are frequently asked questions in interview questions, and they are also points that should be paid attention to in performance optimization. The author will briefly introduce them below.

  • Redrawing : refers to when the elements in the page do not break away from the document flow, but simply change the style, such as modifying the color, background, etc., the browser redraws the style
  • Reflow : refers to the situation where the browser re-renders part or all of the document when the size, position or certain properties of the DOM in the document flow change

In contrast, reflows are more expensive than redraws . In addition, the reading of some properties will also cause reflow, such as reading the height and width of a certain DOM, or using getComputedStylemethods. Avoid reflows and redraws when writing code. For example, the following questions may be encountered in the written test:

Topic: Find the optimization point of the following code and optimize it

var data = ['string1', 'string2', 'string3'];
for(var i = 0; i < data.length; i++){
    var dom = document.getElementById('list');
    dom.innerHTML += '<li>' + data[i] + '</li>';
}

The above code is acquired each time in the loop dom, and then accumulates the internal HTML li, and operates the DOM structure each time, which can be changed to use documentFragmentor traverse the strings that make up the HTML first, and operate once at the end innerHTML.


Summarize

This article summarizes the knowledge points of CSS and HTML frequently tested, including the more important positioning and layout knowledge in CSS, and also introduces some knowledge points concepts and topics of CSS3, as well as the semantics of HTML.

Guess you like

Origin blog.csdn.net/qq_37215621/article/details/130971800