CSS syntax and document flow

The power of CSS

The great thing about CSS is cascading style sheets, which include

  • Style cascading: You can select a style declaration for the same selector more than once
  • Selector cascading: You can declare styles on the same element using different selectors
  • File cascade: Multiple files can be cascaded

The version of CSS

CSS2 is the most widely used version, compatible with all IE, CSS3 is the modern version, after the module upgrade

Caniuse.com Queries compatibility

You can check the compatibility of CSS styles in different browsers on Caniuse

The CSS syntax

Grammar:

The selector {

Attribute name: attribute value;

/ * comment * /

}

Example:

p {
 color: red;
}
Copy the code

Note:

  1. All signs are English signs
  2. Case sensitive
  3. If you make a mistake, the browser doesn’t report an error, it just ignores it
  4. You need a semicolon

Grammar 2: @ grammar

@charset "UTF-8";  /* must be on the first line, plus a semicolon */
@import url(2.css); @media (min-width: 100px) and (max-width: 200px) {Copy the code

The document flow of CSS

The document flow

Document flow refers to the direction in which HTML elements flow

  • If the rightmost part of an inline element is less than one inline element, it is automatically cut in half, with one half on this line and one half on the next line, that is, spanning two lines
  • Blocks flow from top to bottom, each starting on a different line
  • Inline-block elements run from left to right, but do not span two lines

The width of the

  • The width of an inline element is the sum of the internal inline element widths and cannot be specified with width

  • By default, the width of the block element is automatically calculated (width: auto), which is specified by width

  1. The default width of the block element is not 100%, not 100%, not 100%
  2. Never write width: 100% to a Block element;
  • The default width of the inline-block is the sum of the widths of the internal inline elements, which can be specified with width

The inline element is as narrow as possible, and the block element is as wide as possible

highly

  • The height of inline elements is indirectly determined by the line-height (in most cases, inline elements are the same as the line-height, but if the font is different, there is a slight difference, such as 1-2px), regardless of the height
  • The Height of the block element is determined by the internal document flow element and can be set
  • Inline-block elements are the same as block elements

An empty div has a height of 0

An empty span element is not going to have a height of zero, because the height of the span element is line-height and the question is, what if I set the height to be less than the height of the content element? This is overflow

The overflow

  • The overflow is hidden
  • The problem is, if the width and height of the content are not overflowing, there will be a scroll bar
  • Overflow: Auto: Flexible display of scrollbars that only appear when needed
  • Overflow: visible: displays the Overflow part directly

Overflow can be divided into overflow-x and overflowy

Out of document flow

The height of the block element is determined by the internal document flow element, which means that if the element is outside the document flow, the block element will not calculate its height. There are two ways to get out of the document flow:

  1. position: absolute
  2. float: left

CSS box model

Two kinds of box models

  1. Content-box: Width is just the width of the content
  2. Border-box: Width includes the width of content + padding + border

For example, if you write the following code:

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
  	.content-box {
  margin:25px;
  border: 5px solid red;
  padding: 10px;
  box-sizing: content-box;
  width: 100px;
}

.border-box {
  margin:25px;
  border: 5px solid red;
  padding: 10px;
  box-sizing: border-box;
  width:100px;
}
  </style>
</head>
<body>
  <div class="content-box"> </div>
  <div class="border-box"> </div>

</body>
</html>
Copy the code

Although both boxes are set to the same width of 100Px, you can see that the width of the two boxes is different from that of the content box model: only the content width is 100Px,

Border-box model: padding + border + content = 100px

Margin merging

Brothers merged

The margin-bottom of the first div will merge with the margin-top of the second div

Father and son combination

The top margin of the parent will overlap with the top margin of the first child, and the bottom margin of the parent will overlap with the bottom margin of the last child

This margin merge only exists with the top and bottom margins, left and right margins will not merge

Cancel Margin merge

For sibling merge: use display:inline-block

For parent-child merges:

  • The first method is to Border the parent
  • The second method is to add a Paddingmargin to the parent, because there is nothing else between the parent and the parent. If you add a border or Padding, you add something between the parent and the parent, so you cannot merge the Margin
  • The third way is to add Overflow :hidden to parent

The basic unit

The length of the unit

Font-size: 14px; font-size: 14px

Try to draw a rainbow to practice demonstration link js.jirengu.com/feladihete/…

Conclusion:

  • Solve margin merge with overflow:hidden
  • Parent div represents all divs under parent
  • Parent >div The first div under parent

CSS layout

Float layout

Steps:

  • Add float:left, and width to the child element
  • Parent element plus.clearFix
  1. Parent element plus class: class=” clearFix”
  2. Clearfix = clearfix = clearfix
.clearfix::after {
  content:' ';
  display:block;
  clear:both;
}
Copy the code

Some lessons:

  • The last child element does not set width, or sets max-width
  • Img set the Max – width
  • If there is more space below the image, write vertical-align: top or middle
  • If the border is interfering with the layout, you can use outline: 1px solid red. Outline does not take up the space
  • Margin: 0 auto; Or margin – left: auto; margin-right: auto; (better than the former, because it does not affect the upper and lower margins)
  • Key to average layout: negative Margin

Float layouts require manual width calculation, which is cumbersome, but flex layouts are fine

Flex layout

align-items: stretch; Make the item the same height even if the content height is different

Properties of item:

  • Order: Default is 0

List negative, 0, and positive numbers in order from smallest to largest

  • flex-grow

Tip: For a three-column layout, leave the two sides unset and set the middle flex-grow:1.

Actual combat analysis:

There are two ways to make the navigation go to the right

  • On the parent element, set text -content:space-between;
  • Or write margin-left: auto on the navigation bar

When writing an average layout, even using Justify-content: space-between does not work:

The first line is correct, but the second line is wrong, so we still need to use negative margin

First, attach a wrapper div to the Image

Then add negative Margin. The value of negative Margin is the value of the margin-right of each Image

.imageList > .wrapper {
  display: flex;
  flex-wrap: wrap;
  margin-right: -12px;
}
Copy the code
Preview address:

Js.jirengu.com/hiwalumapu/…

Practice flex layout mini games: flexboxfroggy.com/#zh-cn

The grid layout

grid-template-columns: 40px 50px auto 50px 40px; grid-template-rows: 60px 400px 200px; Said five columns 3 rows Usage shows: js.jirengu.com/yuwifamowe/…

Usage: of fr js.jirengu.com/zokevujila/…

To achieve an average layout with fr, don’t need to write a negative Margin js.jirengu.com/somodiyoda/…

Grid usage Summary:
  1. Design the general layout using grid-template-Areas

Example:

 grid-template-areas:
    "big mid1"
    "big mid2"
    "sm1 mid2"
    "sm2 mid3"
    "sm3 mid3"
Copy the code
  1. Use grid-template-rows and grid-template-columns to specify the height and width of each column in each row

Example:

grid-template-rows: 240px repeat(4, 120px);

grid-template-columns: 250px 250px;
  1. For each of these areas, use the grid-area and grid-template-Areas layout strings

Example:

.demo > .image:first-child{
  grid-area: big;
  border: 1px solid red;
}
Copy the code
Grid is especially good for irregular layouts

Suppose we want to do the following layout:

Example code:

Js.jirengu.com/qififesuga/…

CSS element center method

The center of the absolute element:

#demo {
 position: absolute;
  left:50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
Copy the code
Grid Layout exercise game:cssgridgarden.com/#zh-cn

CSS animations

What if we wanted to animate a div moving to the left?

There are three ways to do this, and I will first introduce each of them, and then analyze which is best based on browser rendering principles

1. By setting left

Implement sample click: js.jirengu.com/bagow/1/edi…

The core JS code is:

var n = 1
var id = setInterval(() = > {
  console.log(n)
  if (n <= 50) {
    demo.style.left = n / 100 * 300 + 'px'
    n = n + 1
  }else{
    clearInterval(id)
  }
}, 1000 / 30)
Copy the code

The key is to shift the div to the right by changing the left

2. Transform + transition

Transform: translateX in the transform property is translateX and transition is added. Implement case: js.jirengu.com/qotexonazi/…

Core code:

The CSS code:

#demo {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Add a simple style to demo for easy viewing */
  transition: all 1s;
}
#demo.go{
  transform:translateX(100px);
  /* translateX is translateX to the right */
}
Copy the code

The CSS code has two lines of emphasis:

  • transition: all 1s; Let’s make the whole move in 1s,
  • What the transition does is it gives me the beginning and the end, and I fill in the middle frames
  • transform:translateX(100px); TranslateX (100px) is used for the right shift

JS code:

start.onclick = function(){
  demo.classList.add('go');
 // Add a click event to the button, and when the button is clicked, add the go class to demo
}
Copy the code

Realized effect:

3. With animation

The core of an animation is to define the keyframe, where GO is the name of the animation

1The first way to write, usefrom.to
@keyframes go {
  from {transform:none; }to {transform:translateX(100px);}
}

2The second way to write@keyframes go {
  0 {transform:none; }100% {transform:translateX(100px);}
}
Copy the code

Then, write an extra start class that specifies to let GO run for 2 seconds

#demo.start{
  animation:go 2s;
}
Copy the code

JS adds this class:

start.onclick = function(){
  demo.classList.add('start');
 // Add a click event to the button, and when the button is clicked, add the go class to demo
}
Copy the code

Preview effect:

Js.jirengu.com/zofaxafiba/…

A summary of transition

I’m going to start and end an action, and then I’m going to add a transition in between.

Grammar:

/* Apply to 1 property */
/* property name | duration */
transition: margin-right 4s;

/* property name | duration | timing function */
transition: margin-right 4s ease-in-out;

/* property name | duration | timing function | delay */
transition: margin-right 4s ease-in-out 1s;

/* Apply to 2 properties */Separate with commastransition: margin-right 4s, color 1s;

/* Apply to all changed properties */Use all to animate all propertiestransition: all 0.5 s ease-out;
Copy the code

There are some properties that we cannot use transition:

Such as display: block to display: none js.jirengu.com/molonucuxu/…

When we want to make an animated div disappear, there are two ways to do it:

  1. However, after the hover is set to 0, the element still occupies the corresponding space. The Js event that can be used to remove the element is xxxx.onTransitionEnd
demo.addEventListener('transitionend'.function(){
  demo.remove()
})
Copy the code
  1. You can also use visibility: visible to change to hidden

Instead of display: block -> none, use opacity: 1 -> 0 or visibility: visible -> hidden

Summary of animation

Animation component

  • Key frames keyframes
  • Animation attributes

Since we can specify a key frame at any point, animation can be used for more complex animations

Slightly more complicated animations

Suppose you want to shift a div 150 pixels to the left and then 150 pixels down, start the animation after 1 second, and finish it in 2 seconds, and then automatically repeat the animation all the time:

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <title>demo</title>
  <style>
    #demo {
  width: 50px;
  height: 50px;
  background-color: red;
  animation: go 2s linear 1s infinite alternate;
}

@keyframes go {
  0%{
    transform:none;
  }
  50%{
    transform:translateX(150px);
  }
  100%{
    transform:translateX(150px) translateY(150px); }}</style>
</head>
<body>
   <div id="demo"></div>
  <button id="start">start</button>
</body>
</html>
Copy the code

The key to the CSS code is:

  • Define key frames:
@keyframes go {
  0%{
    transform:none;
  }
  50%{
    transform:translateX(150px);
  }
  100%{
    transform:translateX(150px) translateY(150px); }}Copy the code
  • Animation attributes
   #demo{...animation: go 2s linear 1s infinite alternate;
}
Copy the code

Where infinite represents infinite motion; Alternate means to move back and forth

If you want to add a pause and continue function, how do you do it?

Each property of an animation has a corresponding property name. For example, the name of the property that controls the pause and continuation of the animation is animation-play-state. After knowing the name and value of the property, you can modify the value of the property to achieve the function:

<! DOCTYPEhtml>
<html>

<head>
    <meta charset="utf-8">
    <title>demo</title>
    <style>
        #demo {
            width: 50px;
            height: 50px;
            background-color: red;
        }

        #demo.begin {
            animation: go 2s linear 1s infinite alternate;
        }

        @keyframes go {
            0% {
                transform: none;
            }

            50% {
                transform: translateX(150px);
            }

            100% {
                transform: translateX(150px) translateY(150px); }}</style>
</head>

<body>
    <div id="demo"></div>
    <br>
    <button id="start">start</button>
    <button id="pause">suspended</button>
    <button id="goOn">Continue to</button>

    <script>
        start.onclick = function () {
            demo.classList.add('begin');
        }
        pause.onclick = function () {
            demo.style.animationPlayState = 'paused';
        }
        goOn.onclick = function () {
            demo.style.animationPlayState = 'running';
        }
        // Note the difference between animationPlayState and animationPlayState
    </script>
</body>

</html>
Copy the code
The results are as follows:

Principles of Browser Rendering

By analyzing the browser rendering principle, analyzing animation and Transform + Transition is better than changing Left directly

Browser rendering process:

  1. Build the DOM tree from the HTML tags
  2. Building a CSS Tree from CSS (CSSOM)
  3. Merge the two trees into a render tree
  4. Layout (document flow, box model, calculate size or location, etc.)
  5. Paint (border color, background color, shadow, etc.)
  6. Compose (display the screen according to the cascading relationship)

Three ways to update styles

  1. JS/CSS > Styles > Layout > Draw > Composition

Depending on the browser’s rendering principles, if the developer updates the style (i.e., the geometric attributes of the element, such as width, height, position, etc.), the browser will check all the attributes and then redraw, and finally recompose. The change left method we used before causes the browser to rearrange, render, and compose each time

  1. JS/CSS > Styles > Draw > Composition

If the developer only updates the paint only properties (such as background, text color, etc.), the browser does the drawing directly because it does not affect the page layout.

  1. JS/CSS > Styles > Compositing

When the developer simply changes a property that neither changes the layout nor needs to be drawn, the browser will only perform composits, such as animation and Transform.

You can use the following url to query the different processes triggered by different CSS properties:

csstriggers.com/

This article is the original article of FJL, the copyright belongs to myself and hungry people valley all, reprint must indicate the source