Impact of negative margin on layout

In document flow, the final boundary of an element is determined by margin. When margin is negative, the boundary of the element is inward. Document flow only recognizes this boundary, regardless of your actual size.

In a document stream, if the element preceding the element is set to negative margin, it will follow as a stream. So if you set negative margin on all elements, overwrite will occur.

Margin sets the reference for moving: There are two types of margin guides. The first is top and left, and the elements outside of them serve as the reference to make them move. The other are right and bottom, which use themselves as guides. Make the sibling element move

In general, when margin-top and left are negative, the distance between the guide line and them decreases. When margin-right and bottom are negative, the guide line (not itself, but the one separated by them) moves to the left or above.

performance

While margin can be applied to all elements, the performance varies depending on the display attribute

  • The block element can use margin values in four directions

  • Margin values for inline elements using the upper and lower directions are invalid

    <style> * { margin: 0; padding: 0; } span { border: 1px solid black; margin: 100px; <span style> <span style> <span style>Copy the code
  • Inline-block using a negative margin in the upper and lower direction looks invalid

    • Vertical-align :baseline/bottom; top/middle :baseline/bottom

      <style> * { margin: 0; padding: 0; } input { margin-top: -100px; vertical-align: bottom; < span style =" box-sizing: border-box! Important; word-wrap: break-word! Important;"Copy the code

[Note] Inline-block using a negative margin for the upper and lower direction just looks invalid. This is related to the default vertical-align:baseline, which shows a different visual effect when the vertical-align property is set to another value

overlap

Margin does not always override the preceding elements. It is related to the element display attribute

  • When two block elements overlap, the following element can override the background of the preceding element, but not its content

    * { padding: 0; margin: 0; } .top { width: 100px; height: 100px; background-color: yellow; } .bot { width: 100px; height: 100px; background-color: blue; margin-top: -100px; <div class="top"> <div class="bot"></div>Copy the code
  • When two inline elements, or two line-block elements, or inline and inline-block elements overlap, the following element can override the background and content of the preceding element

        .st {
          background-color: yellow;
          opacity: .8;
        }
    ​
        .sb {
          background-color: blue;
          margin-left: -30px;
          opacity: .8;
        }
      </style>
    ​
      <div class="top">top</div>
      <div class="bot"></div>
    ​
      <span class="st">sttttttttttttttttt</span>
      <span class="sb">sbssssssssssssssssssss</span>
    Copy the code
  • When an inline element (or inline-block element) overlaps a block element, the inline element (or inline-block element) overrides the background of the block element, and in the case of content, the following element overrides the preceding element

    <style> span { background: red; margin-left: -5px; } div { background: blue; width: 100px; float: left; height: 100px; <span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; white-space: inherit! Important;"Copy the code

To sum up, as I understand it, in a normal flow layout, the browser divides the page layout into content and background, with the content always cascading above the background. A block element is divided into content and background, while an inline or inline-block element is itself content (including style Settings such as its background)

When the elements are floating

  • When margin is set to all negative values, elements will be moved normally, but floating elements will overwrite some floating elements

  • This is not what we thought. If we set the same margin on several elements, they will all move the same distance, but they will still hide each other

      <style>
        div {
          border: 1px solid black;
          margin-top: -50px;
          width: 200px;
          height: 200px;
        }
      </style>
    ​
      <div class="box1">1</div>
      <div class="box2">2</div>
      <div class="box3">3</div>
    Copy the code
  • If you add negative margin to only one element of a floating element, it will behave as if it were inline

    <style>
        div {
          float: left;
          width: 100px;
          height: 100px;
          background: red;
        }
    ​
        div:nth-child(1) {
          background: blue;
        }
    ​
        div:nth-child(2) {
          background: green;
          margin-left: -10px;
        }
      </style>
    ​
      <div class="box1">1</div>
      <div class="box2">2</div>
      <div class="box3">3</div>
    Copy the code

Positioning elements

  • For relative positioning, the original position of the element will be vacated by the value deviation of margin, but the original position of the element will still exist by the deviation of left and other factors

  • However, absolute positioning elements are different. It adds the same negative margin to all positioning elements, so that the whole will move without overshadowing each other

```
  <style>
    * {
      margin: 0;
      padding: 0;
    }
​
    div {
      border: 1px solid black;
      position: absolute;
      width: 200px;
      height: 200px;
    }
​
    .box2 {
      left: 200px;
      margin-left: -100px;
    }
​
    .box3 {
      left: 400px;
      margin-left: -100px;
    }
  </style>
​
  <div class="box1">1</div>
  <div class="box2">2</div>
  <div class="box3">3</div>
```
Copy the code

The impact on oneself

  • If the element has no width attribute or (width: auto), negative margin will increase the width of the element.

    <style> .container { margin: 0 auto; width: 500px; border: 1px #ccc solid; margin-bottom: 20px; } .box1 { margin-left: -20px; /* margin-bottom: -100px; */} <div class="container"> <div class="container"> <div class="box1"> I Dont have the width </div>Copy the code

Inline elements

  • If you change the margin of only one inline element to negative, all successive inline elements immediately following it will also move without changing the layout

    <style> * { margin: 0; } .box2 { margin-left: -20px; background: red; } span { border: 1px solid black; } </style> <span class="box1">1111</span> <span class="box2">2222</span> <! -- <div>0000</div> --> <span class="box3">3333</span>Copy the code

Double wing layout

  • Put the middle layout at the front, because we use margin negative value to overwrite the elements in front of it, and the middle element is the widest, just covered.

  • Margin-left: -100%;

  • Right layout marfin-left: – width of itself

  • Wrap the middle element with a div, so that the middle content is not overwritten, and set the child element margin to stretch the distance from the parent element.

    <style> * { padding: 0; margin: 0; } .content { margin: 10px; } .left { width: 300px; height: 200px; float: left; background: red; margin-left: -100%; } .middle { height: 200px; background: blue; Margin: 0 310px; /* margin: 0 310px; } .content-main { width: 100%; float: left; } .right { width: 300px; height: 200px; float: left; background: skyblue; margin-left: -300px; } </style> <div class="content"> <div class="content-main"> <div class="middle"></div> </div> <div class="left"></div> <div class="right"></div> </div>Copy the code

The holy grail layout

  • The layout is the same as the wings, but to avoid overwriting the content of the elements in the middle, you need to set the padding to make the content appear in the middle and not be overwritten.

        <style>
        * {
          margin: 0;
          padding: 0;
        }
    ​
        /* .content {
          padding: 0 310px;
        } */
    ​
        .left {
          width: 300px;
          height: 200px;
          float: left;
          background: red;
          margin-left: -100%;
          /* position: relative;
          left: -310px; */
        }
    ​
        .middle {
          width: 100%;
          height: 200px;
          float: left;
          box-sizing: border-box;
          padding: 0 310px 0 310px;
          background: blue;
        }
    ​
        .right {
          width: 300px;
          height: 200px;
          float: left;
          background: skyblue;
          margin-left: -300px;
          /* position: relative;
          right: -310px; */
        }
      </style>
      
      <div class="content">
        <div class="middle">333333333333</div>
        <div class="left"></div>
        <div class="right"></div>
      </div>
    Copy the code

The Grail and the wings are different

The Grail layout solves the same problem as the twin-wing layout, which is a fixed width on both sides and an adaptive three-column layout with the middle column placed in front of the document stream to render first.

  • The two methods have the same basic idea: first, make the width of the middle box 100% occupy the space of the same height. When the left and right boxes are squeezed out of the area where the middle box is, use the negative value of margin-left to pull the left and right boxes back to the space of the same height as the middle box. Next, make some adjustments to prevent the contents of the middle box from being obscured by the left and right boxes.

  • The main difference is how to keep the contents of the middle box from being obscured by the left and right boxes:

    • Holy Grail layout: Set the padding value of the parent box to leave space for the left and right boxes, and then use the relative layout to adjust the left and right boxes to occupy the space created by the padding.
    • Add another subbox to the middle box, and set the margin value of this subbox to make room for the space without adjusting the left and right boxes.

In simple terms, the wings layout creates one more div than the cup layout, but there is no relative layout, and there are fewer properties.

Such as the layout

  • Using the flex

  • Display: table-cell; display: table-cell; < span style = “box-sizing: border-box; color: RGB (74, 74, 74)

  • Use margin-bottom negative values and padding-bottom positive values

    • Margin-bottom values allow the parent element to be above the child element’s lower margin, allowing the padding-bottom added content to overflow. Then use overflow: hidden to hide it.
    • A margin-bottom positive value increases the content height of the child element to compensate for a margin-bottom negative that causes the parent element to be above the child element. And it’s still visually possible to show the increased height of the child element content.

The classic problem of the box model

Margin overlay problem:

  • Margin-top,margin-bottom, if one is set to negative margin, then it will set the value of the positive and negative values to margin. If both values are negative, then take the smaller negative value.
  • For the superposition of parent and child elements, since the margin-top and margin-bottom of the child elements will be passed to the parent element, a larger margin will be superimposed with the margin set by the parent element, and the smaller margin value will be ignored

Margin passing problem

Margin-top passing. If the top line of the block-level element overlaps the top line of the parent element, then the margin-top value of the block-level element is passed to the parent element. This wouldn’t happen if the tops didn’t overlap

<style> div:nth-child(1) { background: red; width: 100px; height: 100px; margin-bottom: -20px; overflow: hidden; } div:nth-child(2) { background: blue; width: 100px; height: 100px; margin-top: -10px; Opacity: 0.5; } </style> // spacing -20px <div>1</div> <div>2</div>Copy the code

Margin-bottom passing. If the bottom line of the block-level element overlaps the bottom line of the parent element, and the height of the parent element is Auto, then the margin-bottom value of the block-level element is passed to the parent element.

Solution:

  • Set padding-top\padding-bottom for the parent element
  • Set border to parent element
  • Trigger BFC, set overflow: auto/hidden/scroll for parent element

In general: margin is used to set the spacing between sibling elements.

Padding generally sets the spacing between the parent and child elements.

Centered layout

  • Select Centering CSS: A Complete Guide for Each position, including horizontal, vertical, and horizontal/vertical Centering scenarios. There are demonstration examples and corresponding HTML and CSS code

The general structure of the article:

  • Horizontal center

    • For inline elements/block-level elements with text inside/inline block elements (inline-block) :text-align: center;
    • For block-level elements (blocks) : Sets the width andmarigin-leftmargin-rightIs set to auto
    • For multiple block-level elements: set on the parent elementtext-align: center;, set the child elementdisplay: inline-block;; Or use flex layouts
    • For any element, the parent element sets Flex, and the parent element sets margin: auto;
  • Vertical center

    • For inline elements (inline)

      • Single line: set the upper and lower pandding equal; Or setline-heightheightequal
      • Multiple lines: set the upper and lower pandding equal; Or setdisplay: table-cell;vertical-align: middle;; Or use flex layouts; Or use pseudo-elements
    • For block-level elements: In the following two scenarios, the parent element needs to be laid out relative to each other

      • Known height: Use absolute layout for child elementstop: 50%;And then negativemargin-topPull the child element up half the height
      • Unknown height: Use absolute layout for child elementsposition: absolute; top: 50%; transform: translateY(-50%);
      • Using Flexbox: Select directions,justify-content: center;
  • Horizontal and vertical center

    • Fixed height and width:

      • Let’s start with absolute layouttop: 50%; left: 50%;, and then use negative margin equal to half of the width and height to pull back the child element;
      • Set all four offsets to 0, then set margin: auto;
      • Set the offset with absolute positioningTop: calc(50% - half of its width px); Left: calc(50% - half of its width 50px);
    • Height and width unknown:

      • Let’s start with absolute layouttop: 50%; left: 50%;And then set thetransform: translate(-50%, -50%);
      • By setting the parent element’s line-height equal to height,tex-aligin: center, child element Settingsdisplay:inline-blockSince text-aligin is inherited, the child element needs to be settext-aligin:leftTo change its level display.
    • Use Flexbox: justify- Content: Center; align-items: center;

    • Use child elements to locate absolutely and specify width and height, and parent elements to locate relative. Set left, right, top, bottom to 0. Margin to auto;

            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
      Copy the code

六四运动writing-mode* * attributes

Horizontal or vertical placement of text and the direction of travel of text in block-level elements.

Attribute values:

  • Horizontal-tb: For left-aligned (LTR) scripts, content flows horizontally from left to right. For right-aligned (RTR) scripts, content flows horizontally from right to left. The next water is parallel below the top row.
  • Vertical-rl: For left-aligned (LTR) scripts, content flows vertically from top to bottom, with the next vertical line to the right of the previous one. For right-aligned (RTR) scripts, content flows vertically from bottom to top, with the next vertical line to the left of the previous one.
  • Vertical-lr: For left-aligned (LTR) scripts, content flows vertically from top to bottom, with the next vertical line to the right of the previous one. For right-aligned (RTR) scripts, content flows vertically from bottom to top, with the next vertical line to the right of the previous one.
  • sideways-rl: For left-aligned (LTR) scripts, content flows horizontally from left to right. For right-aligned (RTR) scripts, content flows horizontally from right to left. All glyphs, even in vertical scripts, face to the right.
  • sideways-lr: For left-aligned (LTR) scripts, content flows vertically from top to bottom. For right-aligned (RTR) scripts, the content flows vertically from bottom to top. All glyphs, even in vertical scripts, face to the left.

Responsive layout

Media attribute

@media all and (min-width: 100px) and (max-width: 500px) { }}Copy the code

Remove the floating

Up and down is arranged

  • Clear: both; Can be

Nested arrangement (parent collapses in height, affecting the layout of subsequent elements)

  • In the last parent element plus an empty child element, style bit clear: both;

    • Cons: One more useless tag
  • Sets the parent container to a fixed height

    • Disadvantages: height set dead, not conducive to future maintenance
  • Parent element float, after the element set clear: both;

    • This works, but it affects the layout of the nested elements
  • Parent element set overflow: hidden/auto/scroll

    • Disadvantages: If a child element tries to overflow, it can be affected
  • Parent element Settings display: inline-block/flex/table-cell

    • It affects the next element
  • Use the After pseudo-class

    • Note: Clear: both only applies to block-level elements, inline elements do not work, and inline block elements do not work
    After {content: ""; display: block; clear: both; }Copy the code

BFC

Conditions that trigger the BFC

  • The root element, the HTML element
  • The value of float is not None
  • Overflow value is not visible(hidden, scroll, auto)
  • The display values are inline-block, table-cells, and table-Caption
  • The value of position is absolute or fixed

The characteristics of landing

  1. The internal boxes are placed vertically, one after the other.
  2. The vertical distance of Box is determined by margin. In a BFC, the vertical margin of two adjacent block-level boxes will fold. Fix: margin overlay.
  3. In BFC, the margin-left of each box touches the border-left of the container (or the right edge for right-to-left formats).
  4. The region that forms the BFC does not overlap with the float box. Solution: Implement a two-column layout.
  5. When calculating the BFC height, the floating element also participates in the calculation. Solution: Clear the float.

role

  • The BFC is an isolated, independent container on the page, and the child elements inside the container do not affect the outside elements, and vice versa.

To solve the problem

  • Overlay problem of margin element in the same BFC

    • Set margin on only one element

    • Place the two elements under separate BFC and trigger the BFC using the above conditions

    Add an ellipsis

Width: must; White-space: nowrap// Don't let content break overflow: hidden; Text-overflow: ellipsis; // Add the ellipsisCopy the code

form

display

  • Table: Specifies the table of objects as block element levels. Similar to HTML tags

    (CSS2)

    • You can set margin and padding
  • Inline-table: Specifies a table of objects as inline element levels. Similar to HTML tags

  • (CSS2)

    • Margin and padding can be set, as well as negative margin
  • Table – Caption: Specifies the object as the table title. Similar to HTML tags

  • (CSS2)

    • Margin and padding cannot be set, and the border will not be displayed
  • Table-row-group: Specifies an object as a table row group. Similar to HTML tags

  • (CSS2)

  • Table-column: Specifies an object as a table column. Similar to HTML tags

  • (CSS2)

  • Table-column-group: Specifies an object to be displayed as a table column group. Similar to HTML tags

  • (CSS2)

  • Table-header-group: Specifies an object as the table header group. Similar to HTML tags

  • (CSS2)

  • Table-footer-group: Specifies an object as a table footer group. Similar to HTML tags

  • (CSS2)

    Structural pseudo-class selectors

    Nth-of-type () represents elements of the same type

    Nth-child () represents all elements

    (), can also be 2n(for even rows), 2n+1(for odd rows)

    Css3 background style

    background-size:

    • Only the background image, not the background color
    • Background-image: url() takes effect

    • . px .. Px (width and height) /
    • The background image may show incomplete, the container fully covered
    • The picture is complete and the container may contain space

    When setting dimensions by width and height values, you can provide one or two values:

    • If only one value is given, this value will be the width value and the height value will be set toAuto.
    • If two values are given, the first will be the width value and the second the height value.

    Background-origin (the position where the background image is filled):

    • Only the background image, not the background color
    • Padding-box (default) : Padding in the padding area
    • Border-box: Fills at the border
    • Content-box: Fills in the content

    Note: When usingbackground-attachmentIf fixed, this property is ignored and has no effect.

    Background-clip :(background clip)

    • Both the background image and the color will work here
    • Border-box (default) : A background is displayed on and within the border
    • Padding-box: The padding-box area is the content area where the background is displayed
    • Content-box: Displays the background only in the content area
    • Text (not allowed for test API) : indicates clipping on text. To create a clipping effect, we need to set the text color to **transparent六四运动

    Background-position: Indicates the position of the background image

background-position: right 50px bottom 70px; // This is in the bottom right, then 50px from the right and 70px from the bottomCopy the code

If you don’t add the word right and just write the number offset, its reference point is the upper left corner.

A position defines a set of X /y coordinates (relative to the edge of an element box model) to place the item(Originally as item). It can be defined as one value or two values. If defined as two values, the first value represents the horizontal position and the second represents the vertical position. If only one value is specified, then the second value defaults tocenter.

Background -attachment: How does the background picture follow the text

  • Scroll: indicates that the scroll bar rolls. This key attribute value indicates that the background is fixed relative to the element itself, rather than scrolling with its content (which is valid for element borders).
  • Fixed: Indicates that the position is fixed. This key attribute value indicates that the background is fixed relative to the viewport. Even if an element has a scrolling mechanism, the background does not scroll with the content of the element.
  • Local: scroll with the text. This key attribute value indicates that the background is fixed relative to the content of the element. If an element has a scrolling mechanism, the background will scroll with the content of the element, and the drawing and positioning areas of the background are relative to the scrollable area rather than the border that contains them.

Background-repeat: Overlaps the background image.

  • Space: Images will be repeated as much as possible, but will not crop. The first and last images are pinned to the corresponding edges of the element, and the white space is evenly distributed between the images. That is, the container may not be fully covered.
  • Round: Images are compressed or expanded to fill the container. This depends on the size of the container.

Background-image: cSS3 gradient You can set a number of background pictures, and first set the most close to the user

Pay attention to

<style> div { width: 100px; height: 100px; */ /* Background: red, blue; */ /* background: red, blue; */ /* background: red, url('https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/mirror-assets/171de8ad450b4f25c89~tplv-t2oaga2asx-image.image'); */ background: url('https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/mirror-assets/171de8ad450b4f25c89~tplv-t2oaga2asx-image.image'), red; } </style>Copy the code

Question:

Why is it possible to change the size of a gradient using background-size? And he can set background-size on the background-image.

  • Set background-size to change the overall gradient background size.

Why can I use background-position to set dynamic gradients?

  • Because we can combine it with a completely tiled way, and even if we change the position, it will still be completely filled. I ignored the fact that the background was completely tiled and thought that changing the position would free up some space.
<style> div { width: 500px; height: 20px; border: 1px solid black; background-size: 16px 16px; // The color of the gradient on both sides is 0; linear-gradient(-45deg, #D9CFBB 25%, #C3B393 0, #C3B393 50%, #D9CFBB 0, #D9CFBB 75%, #C3B393 0); animation: panoramic 20s linear infinite; } @keyframes panoramic { to { background-position: 200% 0; } } </style> <div></div>Copy the code

The gradient

Linear gradient

  • The value specified after the gradient color is where the color ends. But the color will transition from the position specified by the previous color to the position specified by the latter color.

  • You can specify a position without a color, or you can specify a color without a position.

  • The default gradient direction is top to bottom

  • You can use the keywords left, bottom, top, right combined with to to indicate the direction of the gradient, or you can use angles to indicate the direction of the gradient

    • 0deg indicates starting from the bottom. A positive value indicates clockwise, and a negative value indicates counterclockwise

      Background-image: linear-gradient(to top, #7A88FF, #7AFFAF);

      Background-image :linear gradient(0deg, #7A88FF, #7AFFAF); background-image:linear gradient(0deg, #7A88FF, #7AFFAF);

  • The number after the color indicates the range of excess. The values set for every two colors are the range, which is slow, not abrupt.

    Background-image: #66CC99; background-image: #66CC99; background-image: #66CC99; background-image: #66CC99; background-image: #66CC99; linear-gradient(45deg, #66CC99 20px, #6666CC 30px, #66CC99 40px)Copy the code

Radial gradient

Gradient shape (default is ellipse) at the center where the gradient starts, color Color range,…

<style> div { width: 200px; height: 120px; #b4a078 */ background-image #b4a078 */ background-image radial-gradient(circle at 100px -8px, transparent 20px, #b4a078 22px); } </style> <div></div>Copy the code

Repeating-linear-gradient Repeats the gradient

div {
  background: repeating-linear-gradient(-45deg, red 0 5px, blue 5px, 10px);
}
Copy the code

Pay attention to

To include a solid non-transitioning color region in the gradient, include two locations where the color starts and ends. Color starting and ending points can have two locations, which is equivalent to two consecutive colors having the same color starting and ending points at different locations. The color will reach full saturation at the start and end of the first color, maintain that saturation to the start and end of the second color, and transition through the first position of the neighboring color start and end to the color of the neighboring color start and end.

. Multiposition-stops {// background-position: linear-gradient(to left, lime 20%, red 30%, red 45%, cyan 55%, cyan 70%, yellow 80% ); // method 2 background: linear gradient(to left, lime 20%, red 30% 45%, Cyan 55% 70%, yellow 80%); }Copy the code

Dynamic gradient

You just have to think about it

<style> div { height: 600px; width: 600px; animation: gradientChange 2s infinite alternate; background-image: linear-gradient(45deg, #FA8BFF 0%, #2BD2FF 52%, #2BFF88 95%); /* background-repeat: no-repeat; */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ background-size: 200% 200%; } @keyframes gradientChange { 0% { background-position: 0 100%; } /* 50% { background-position: 50% 50%; } */ 100% { background-position: 100% 0; } } </style> <div></div>Copy the code

Outline (style,width,color)

And border

  • The outline takes up no space and is drawn around the content of the element.

    div { width: 100px; height: 100px; box-sizing: border-box; border: 5px solid black; outline: 2px solid red; <div></div>Copy the code
  • According to the specification, the outline is usually rectangular, but can also be non-rectangular.

Outline -color: Outline color

Outline -style: Outline style

  • An element contour is a line drawn around an element, outside the border, to make the element stand out

  • None Has no outline (outline-width is 0).

    The outline which was described as a series of points.

    The shell profile is a series of short lines.

    Solid Outlines are solid lines.

    Double Outlines are two lines with gaps. Outline -width is the sum of lines and space.

    Groove profile is concave.

    Ridge is the opposite of groove: the outline is raised.

    The inset profile is embedded.

    Outset is opposite to inset: outset has a prominent outline.

Outline -width: specifies the width of the outline

  • . Px, rem/thin/medium/thick

The outline-offset is used to set the gap between the outline and an element’s edge or border.

  • . Px (plus or minus)

Do something with box-shadow

  • The box-shadow is close to the border-radius rounded corner, so we can make an inner corner box

  • The stroke outline does not fit the rounded border-RADIUS

    <style>
        div {
          background: #fff;
          width: 100px;
          height: 100px;
          border-radius: 10px;
          outline: 5px solid black;
          box-shadow: 0 0 0 4px black;
        }
      </style>
      
      <div></div>
    Copy the code

Small bug about fixed and transform combination

We know position: fixed; The offset is referenced to the entire browser window.

For elements whose transfrom value is not None, position: fixed will be positioned against the nearest ancestor of transform. This is because elements whose transfrom value is not None define a local coordinate system, resulting in a postion: Fixed calculates the layout from this coordinate system. This bug has not yet been fixed. It is recommended to avoid fixed positioning under the transform element.

  <style>
    .parent {
​
      transform: translate(100px, 0);
      border: 1px solid black;
    }
​
    .son {
      position: fixed;
      left: 60px;
      width: 50px;
      height: 50px;
      background: red;
    }
  </style>
  
  <div class="parent">
    <div class="son"></div>
  </div>
Copy the code

How do I use the CSS to implement a scrolling progress bar

body { height: 2000px; background-image: linear-gradient(to right top, #ffcc00 50%, #eee 50%); background-size: 100% calc(100% - 100vh + 5px); background-repeat: no-repeat; } // This is to overlay the gradient below body 5px. body::after { content: ""; position: fixed; top: 5px; left: 0; bottom: 0; right: 0; background: #fff; z-index: -1; }Copy the code

Resolution, pixels, multiples

At the same resolution, the more pixels displayed, the clearer the image.

Resolution is a parameter that measures the amount of data in a bitmap image.

Pixel density describes the number of physical pixel blocks within the range represented by the hypotenuse of one inch.

Device-independent pixels: Pixels in CSS. A device independent pixel is a pixel that exists abstractly. Which means he can be big or small.

Image pixels are virtual pixels. Because it has no fixed size, we can stretch the image to any size we want, and each pixel will be scaled accordingly.

Device pixel ratio: DPR = physical pixels/device independent pixels

The resolution of the picture is the number of horizontal color blocks x the number of vertical color blocks.

  1. Image pixels are blocks of pixels that make up an image. They have no actual size. You stretch and scale an image and the number of pixels doesn’t change.
  2. Device pixels are the thousands of little squares that a device’s screen is divided into. They are physical pixels, and you can calculate the size of each physical pixel based on the length, width and resolution of the device.
  3. CSS pixels, also known as device-independent pixels, are an abstract concept. The 1px looks different to the naked eye on different devices. These are the units that we use when we code.

Some text Styles

White – space: normal (the default) | nowrap | pre | pre – wrap | pre – line

  • Nowrap: never break lines. Multiple common Spaces are combined into one. But it doesn’t interfere</br>The implementation of the.
  • Pre: Short for Preserve, which means save. The actual content on the page is exactly the same as what is written in the HTML tag, including several normal Spaces.
  • Pre-wrap: Short for preserver-wrap. Represents reserved and newline. It’s a combination of the first two attributes.
  • Pre-line: Multiple normal Spaces are combined and wrapped.
(CSS2)

  • Arrange the headings vertically
  • Table-cell: Specifies an object as a table cell. Similar to HTML tags

  • (CSS2)

    • Margin cannot be set, padding can be set
  • Table-row: Specifies an object as a table row. Similar to HTML tags

  • Whether it works A newline Common Spaces Word wrap
    And have spent
    normal x × (Merge) Square root Square root
    nowrap x × (Merge) x Square root
    pre Square root Square root x Square root
    pre-wrap Square root Square root Square root Square root
    pre-line Square root × (Merge) Square root Square root

    Word – break: normal (the default) | break – all | keep – all

    Break-all: Very strong folding. If it’s a long English word, you might cut it off in the middle.

    Keep-all: Only Spaces can trigger wrapping, otherwise the container width will be exceeded. And they don’t break up long words and wrap them.

    Word – wrap (overflow – wrap) : normal | break – word

    Break-word: indicates a less strongly folded line. Words are broken up only when there is no room for one line. Or you’re folding it normally.

    Letter-spacing: sets the spacing between characters.

    If it’s an English word, it means the distance between each letter, not the distance between each word.

    Wor-spacing: Sets the spacing between English words.

    CSS cascading context

    The cascading context is a three-dimensional representation of HTML elements arranged along an imaginary Z-axis relative to the user, assuming that the user is facing a window or web page. The HTML elements occupy this space in order of priority based on their element attributes.

    How to generate a cascading context:

    • Document root element (HTML);

    • Elements whose position is Absolute or relative and whose z-index is not Auto;

    • Elements with a position value of fixed or sticky (Sticky positioning is suitable for all browsers on mobile devices, but older desktop browsers do not support it);

    • The parent element of the display attribute values for the flex | inline – flex, child element z – the index attribute values are not for auto, child elements for cascading context elements;

    • Grid (Grid) is a child of the container, and the z-index value is not auto;

    • Elements whose opacity value is less than 1 (see The Specification for Opacity);

    • Elements whose mix-blend-mode attribute value is not normal;

    • Any of the following elements whose attribute value is not None:

      • transform
      • filter
      • perspective
      • clip-path
      • mask / mask-image / mask-border
    • The value of isolation is the element of ISOLATE.

    • -webkit-overflow-scrolling for elements whose value is touch;

    • The will-change value sets any attribute that, when non-initial, creates elements in cascading context (see this article);

    • Elements whose contain attribute value is layout, paint, or a composite value containing one of them (such as contain: strict, contain: Content).

    Cascading level diagram

    Rules for comparison within the same cascading context.

    Weird test:

    When two parent elements are set to the same Z-index, they’re cascading in the same order, and that’s the dom order in the normal document flow.

    <style>
        * {
          margin: 0;
          padding: 0;
        }
    ​
        .A {
          position: relative;
          z-index: 1;
        }
    ​
        .B {
          position: relative;
          z-index: 1;
        }
    ​
        .a {
          position: absolute;
          background: red;
          width: 100px;
          height: 100px;
          z-index: 5;
        }
    ​
        .b {
          position: absolute;
          top: 100px;
          background: blue;
          width: 100px;
          height: 100px;
          margin-top: -50px;
        }
      </style>
      
       <div class="A">
        <p class="a">a</p>
      </div>
      <div class="B">
        <p class="b">b</p>
      </div>
    Copy the code

    The layer level of the background/border of an element is less than the layer level of an element whose Z-index value is less than 0.

    <style> .box { display: flex; } .parent { width: 200px; height: 100px; background: #168bf5; /* z-index: 1; /* z-index: 1; /* z-index: 1; } .child { width: 100px; height: 200px; background: #32d19c; position: relative; z-index: -1; } </style> <div class="box"> <div class="parent"> parent <div class="child">child</div> </div> </div>Copy the code

    Conclusion:

    • Cascading contexts can be contained within other cascading contexts and together create a hierarchy of cascading contexts.
    • Each cascading context is completely independent of its siblings: only child elements are considered when dealing with cascading.
    • Each cascading context is self-contained: when the contents of an element are cascading, that element as a whole is cascading in order within the parent cascading context.
    • When comparing the cascading levels of elements, they all need to be in the same parent cascading context.
    • Z-indexes in children of different parent cascading contexts are not compared.

    Learn from yourself

    will-change

    Provides a way for Web developers to inform the browser of changes to the element so that the browser can optimize the element attributes before they actually change. This optimization can prepare some of the complex calculations ahead of time, making the page more responsive and responsive.

    Don’t apply will-change to too many elements

    Give it plenty of time to work: Use it by trying to find some way to know in advance that the element is likely to change, and then add the will-change attribute to it. It is recommended to add before the change element. For example, if we want a border shadow on the move in element, we can apply this style to the children of the move in and element.

    <style> div { position: relative; padding: 1em; background-color: #fff; } div:before { content: ""; position: absolute; top: 0; right: 0; bottom: 0; left: 0; /* z-index: -1; */ box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3); opacity: 0; will-change: opacity; - its - the transition: 0.2 s; The transition: 0.2 s; } div:hover:before { opacity: 1; } </style> <div> <p> DWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWD right man man man more than the surface-to-surface missile to man man man, many, many, many, many more < / p > </div>Copy the code

    Meta tags

    If the name attribute is set, the Meta element provides document-level metadata that applies to the entire page. Used in combination with Content, the metadata is provided to the document as a name-value pair, where name is the name of the metadata and content is the value of the metadata.

    • Common values: keywords, description, viewport

      Keywords: Set keywords, content for the keyword to be set, conducive to the search engine search.

      Description: Description of the page, content is the description text, conducive to search engine search.

      Viewport: This provides hints about the initial size of the viewport and is only for mobile devices. Content represents some Settings for mobile.

      Value Possible values describe
      width A positive integer or stringdevice-width Define the width of the Viewport in pixels units.
      height A positive integer or stringdevice-height Define the height of the Viewport in pixels units.
      initial-scale A 0.0A positive number between 10.0 Defines the zoom ratio between the device width (device width in portrait mode or device height in landscape mode) and viewport size.
      maximum-scale A 0.0A positive number between 10.0 Define the maximum scale; It has to be greater than or equal tominimum-scaleOtherwise, uncertain behavior will occur.
      minimum-scale a0.010.0Positive between Define the minimum value of scaling; It has to be less than or equal tomaximum-scaleOtherwise, uncertain behavior will occur.
      user-scalable A Boolean value (yesorno) If you set it tonoUsers will not be able to zoom in or out of the web page. The default value isyes.

    If the http-equiv attribute is set, the meta element is a compilation directive that provides the same information as a similarly named HTTP header.

    • Common values: Content-type, refresh, expires

      Content-type: set the content to text/ HTML. charset=utf-8

      Refresh, how long (in seconds) it takes for a web page to refresh itself or for a web page to automatically link to another web page. If the value of content is set to an integer, it indicates how many seconds to refresh the web page. If the VALUE of URL is set, it indicates how many seconds to jump to the specified URL.

      <meta http-equiv="refresh" content="2; Url = HTTP: / / http://39.97.212.45:3000/ ">Copy the code

      Expires specifies the expiration time of the cached document. Once the page expires, it must be rerequested from the server. Content sets the expiration time. The format must be GMT

      <meta http-equiv="expires" content="Wed, 17 Jun 2020 00:00:00 GMT" >
      Copy the code

    If the charset attribute is set, the Meta element is a charset declaration that tells the document which character encoding to use.

    <meta charset=" utF-8"Copy the code

    reference

    MDN

    zhihu

    The link tag

    Rel: represents the relationship between the link mode and the document that contains it.

    • Icon, to import the document icon
    • Stylesheet, which means to introduce CSS resources
    • Preload, which means the browser should preload the resource, and the use of this property must depend on as, whose value represents the type of content being loaded

    Href: an imported link.

    Media: indicates the conditions under which the link takes effect.

    Disabled: disables imported links.

    Dns-prefetch: This property identifies the resource that may be required for the next navigation and should be retrieved by the user agent. This allows the user agent to respond more quickly to future resource requests.

    Title: The attribute has special semantics on the element. When used for stylesheet, it defines a preferred stylesheet or alternate stylesheet. Using it incorrectly can cause the stylesheet to be ignored. If the link tag has a title attribute, it will only load the style file introduced by the first link. If there is a link tag without a title, it represents a permanent style file, and the later one overwrites the previous one.

    <meta charset=" utF-8 "> <meta name="viewport" content="width=device-width, initial =1.0"> <! Href ="./ CSS /style3.css" title="base3"> <! This style overrides the previous one. > < span style =" text-align: center; text-align: center; Href ="./ CSS /style2.css" title="base2"> <! -- <link rel="stylesheet" href="./css/style3.css" title="base3"> --> <title>Document</title> </head> <body> <div></div> <span> </span> </body>Copy the code

    Reference to the MDN

    CSS Performance Optimization

    Inline First screen Critical CSS

    Inline CSS allows the browser to start rendering the page earlier because it can be rendered after the HTML has been downloaded.

    One disadvantage of inline CSS, however, is that the inline CSS is not cached and will be redownloaded every time. As mentioned above, this doesn’t seem to be a big deal if we keep the inline file size to 14.6 KB.

    Loading the CSS asynchronously

    Add tags dynamically through JS.

    Const myCSS = document.createElement("link"); myCSS.rel = "stylesheet"; myCSS.href = "mystyles.css"; / / insert to the header of the final location document. The head. The insertBefore (myCSS, document.head.childNodes[ document.head.childNodes.length - 1 ].nextSibling );Copy the code

    Remove unwanted CSS

    Through the Uncss library.

    Use CSS selectors effectively

    Keep it simple and don’t use too many complex selectors.

    Wildcards and attribute selectors are the least efficient and have the most elements to match, so avoid them.

    Do not decorate element tags with class selectors and ID selectors, such as P.A. This is unnecessary and inefficient.

    Don’t sacrifice readability and maintainability for speed.

    Do not use @import to import CSS files

    First, using @import to introduce CSS affects the browser’s parallel downloads. After the CSS file is downloaded and parsed, the browser will know that another CSS file needs to be downloaded. Then it will download the CSS file and begin parsing, building the Render tree, and so on. This prevents the browser from downloading the desired style files in parallel.

    Analyze and compare the advantages and disadvantages of opacity: 0, visibility: hidden, and display: None and the applicable venues

    1. Display: None (occupies no space, cannot be clicked) (scene, shows structure that does not exist here)
    2. Visibility: hidden (occupies space, cannot be clicked) (Scene: display will not change the page structure, will not be spread)
    3. Opacity: 0 (occupies space and can be clicked) (Scene: can be paired with Transition)

    Structure: display:none: the element will completely disappear from the render tree, and does not occupy any space during rendering, which cannot be clicked; visibility: hidden: The element will not disappear from the render tree, and the render element will continue to occupy space, but the content is not visible, which cannot be clicked: 0 Elements do not disappear from the render tree. Render elements continue to occupy space, but the content is not visible and can be clicked

    Inheritance: display: none and opacity: 0: the properties are not inherited. The descendant node disappears because the element disappears from the render tree. Therefore, modifying the attributes of the descendant node cannot be displayed. Visibility: hidden: is an inherited property. The descendant node disappears due to the inheritance of hidden. You can make the descendant nodes explicit.

    Display: None: Modifying an element causes document backflow and the screen reader does not read the element content. The performance consumes a large amount of visibility:hidden: Modifying an element only causes redrawing of the element, and the performance consumes a small amount of visibility. The screen reader reads the visibility: Hidden Element content Opacity: 0: Modifying an element causes repainting, which consumes less performance

    Connections: Both make elements invisible

    Border background border-image

    /* border-image: image-source image-height(a multiple of the border width) image-width image-repeat */Copy the code
     <style>
        .box1 {
          border: 30px solid transparent;
          padding: 20px;
          border-image: url("https://mdn.mozillademos.org/files/4127/border.png") 30;
        }
    ​
        .box2 {
          border: 30px solid transparent;
          padding: 20px;
          border-image: linear-gradient(red 49%, green 50%) 30;
        }
      </style>
    </head>
    ​
    <body>
      <div class="box1"></div>
      <div class="box2"></div>
    </body>
    Copy the code

    Weight of the selector

    CSS basic selectors include ID selector, class selector, label selector, and wildcard selector. Below normal circumstance, can answer commonly! Important > Inline Style > ID Selector > Class Selector > Tag Selector > Wildcard Selector.

    The triangle

    1. The use of border

    2.clip-path

    .triangle { width: 30px; height: 30px; background: red; clip-path: polygon(0px 0px, 0px 30px, 30px 0px); Transform: rotate(225deg); transform: rotate(225deg); transform: rotate(225deg); // Rotate 225 to become the lower triangle}Copy the code

    clip-path

    /* The first four values refer to the distance from the sibling element. Top right bottom left. The following values represent the radians of the four corners of the inserted rectangle. */ clip-path: inset(35% 35% 35% 35% round 0 70% 0 70%); SQRT (width^2+height^2)/ SQRT (2), where width and height are the width and height of the correlation box model. The center position is determined by the width and height of the correlation box model. X: Width conversion. Y: Height conversion. */ clip-path: circle(25% at 50% 50%); The radius and the length of the center of the circle expressed in percentage will refer to the width and height of the box model, with width as the reference value of Rx and height as the reference value of RY. */ clip-path: ellipse(25% 25% at 50% 50%); /* The x coordinate of the percentage value is referenced by the width of the model and. The y coordinate is based on the height of the model and theta. */ clip-path: polygon(50% 0, 25% 50%, 75% 50%);Copy the code

    What does 1REM, 1em, 1vh and 1px mean?

    rem

    Rem is the total length of the element relative to the root element. It is common practice to give HTML elements a font size and then give the rest of the elements length units of REM.

    em

    • The em of the child element font size is relative to the parent element font size
    • Elements of width/height/padding/margin with em words is relative to the element of the font size

    vw/vh

    Viewport Width and Viewport Height are equal to 1% of the screen Width and Height. However, % is more appropriate for Width and VH is better for Height.

    px

    Px pixels. A unit of relative length. The pixel PX is relative to the display screen resolution.

    General computer resolution {1920*1024} and other different resolutions

    1920*1024 The former is the width of the screen with a total of 1920 pixels, the latter is the height of 1024 pixels

    The difference between pseudo-classes and pseudo-elements

    Pseudo classes:

    1. Is to select the state of an element that a normal selector cannot select.
    2. Since state changes are non-static, when an element reaches a particular state, it may get a pseudo-class style; When the state changes, it loses this style again.
    3. Use single quotation marks

    Pseudo elements:

    1. The set document stream does not exist for content that is a virtual container.
    2. At its core is the need to create elements that do not normally exist in documents.
    3. It is indicated by double quotation marks

    Similarities:

    • Neither pseudo-classes nor pseudo-elements appear in the source file nor in the DOM tree. In other words, pseudo-classes and pseudo-elements are not visible in HTML source files.

    Differences:

    • Pseudo-classes are actually different states based on ordinary DOM elements. They are a certain feature of DOM elements.
    • Pseudo-elements can create abstract objects that do not exist in the DOM tree and are accessible.

    CSS Naming Conventions

    BEM named

    Where, block represents an independent block or component; Independent means that this part can be displayed and used in other parts, it does not depend on its parent or sibling elements. Element represents the finer grained elements in each block; The modifier is usually used to indicate the different types and states of the block or element.

    .block {}
    .block__element {}
    .block--modifier {}
    .block__element--modifier {}
    ​
    Copy the code

    vertical-align

    Vertical-align specifies the vertical alignment of inline or table-cell elements. Only inline and table-cell elements can be used. It cannot be a line-block. So if we center the image, we can only set its type to table-cell.

    div { display: table-cell; height: 500px; width: 900px; border: 1px solid black; text-align: center; /* The CSS attribute vertical-align specifies the vertical alignment of inline or table-cell elements */ vertical-align: middle; }Copy the code

    text-align

    The text-align CSS property defines how inline content, such as text, should be aligned against its block parent. Text-align does not control the alignment of the block element itself, only the alignment of its inline content.

    The difference between link and @import

    • Styles in @import have the lowest priority. The interior style will also override him.
    • Link is an HTML tag, and @import is provided in CSS
    • While the link is loaded at the same time as the page is loading, the @import CSS reference is loaded after the page has loaded
    • @import is only recognized in IE5 and above, while link is an HTML tag and does not cause browser compatibility problems
    • Link introduces a style with a greater weight than the @import reference (@import imports the referenced style into the current page)

    What does Doctype do? The difference between strict mode and promiscuous mode?

    Used to tell the browser in which mode to render the document

    In strict mode: Page layout and JS parsing are performed to the highest standards supported by the browser.

    Promiscuous mode: not strictly followed by standards, mainly used for compatibility with older browsers, backward compatibility.

    Easily switch between pictures

    img:hover{
        content: url(path);
    }
    Copy the code

    Content only changes the visual presentation. When we save the image with the right mouse button or other form, we still save the original SRC image. This method can also be used on the official website logo.

    Since it is not possible to set the size of the images generated with Conetnt, it is recommended to use SVG images for mobile use.