Some common basic concepts

  • Physical Pixel: Also known as device pixels, it is the tiniest physical part of the display device. Each pixel can be set to its own color and brightness according to the operating system
  • Density independent Pixel: Device-independent pixels, also known as density-independent pixels, can be thought of as a point in a computer coordinate system that represents a virtual pixel (such as a CSS pixel) that can be used by a program and then converted into a physical pixel by the relevant system
  • CSS pixel: CSS pixel is an image extraction unit, mainly used in browsers to accurately measure the content on Web pages. CSS pixels are generally called device-independent pixels, or DIPs for short
  • Screen density (PPI): Screen density is the number of pixels on a device’s surface, usually measured in pixels per inch
  • Device Pixel Ratio: DPR defines the mapping between physical pixels and device-independent pixels
    • Device pixel ratio = physical pixels/device-independent pixels
    • In JS, you can use window.devicePixelRatio to obtain the DPR of the current device
    • In the CSS, you can run the -webkit-device-pixel-ratio, -webkit-min-device-pixel-ratio, or -webkit-max-device-pixel-ratio command to query media. Do some style adapter devices of different DPR, or use the resolution | min – resolution | Max – resolution of these relatively new standard way

  • Bitmap pixel
    • A bitmap pixel is the smallest data unit of a raster image (e.g. PNG, JPG, GIF, etc.). Each bitmap pixel contains some of its own display information (e.g. Display position, color value, transparency, etc.).
    • In theory, one bitmap pixel corresponds to one physical pixel, so the image can be displayed perfectly and clearly, as shown in the following figure: For the Retina screen with DPR =2, one bitmap pixel corresponds to four physical pixels. Since a single bitmap pixel cannot be further divided, the color can only be taken nearby, resulting in blurred images
    • For image hd problems, a better solution is to double the image (@2x), such as 200×300(CSS Pixel) IMG tag, need to provide 400×600 image

  • Zoom ratio scale: scale = 1 / DPR
  • Windows viewportViewport is exactly the width and height of the browser window. On a desktop browser, a viewport is the width and height of the browser window, but on a mobile device, it is a bit more complicated. Recommended reading:Interpretation of ViewPort – web adaptive mobile app magic device
  • Media enquiries @media
    • A media query consists of an optional media type and zero or more expressions that limit the range of stylesheets using media capabilities, such as width, height, and color. Media queries have been added to CSS3 to allow the presentation of content to be tailored to a specific range of output devices without changing the content itself, which is perfectly suited to web pages responding to different types of devices
    • Media queries contain an optional media type and, subject to the CSS3 specification, zero or more expressions that describe media characteristics and will eventually be resolved to true or false. If the media type specified in the media query matches the device type used in the presentation document and all expressions are true, the media query results in true and the style in the media query takes effect
    <! CSS media query in link element --><link rel="stylesheet" media="(max-width: 800px)"   href="example.css" /><! CSS media query in stylesheet --><style>
    @media (max-width: 767px) {...cssThe code... }@media (min-width: 768px) and (max-width: 991px) {...cssThe code... }</style>
    Copy the code

    Recommended reading: Follow the circle – a comprehensive understanding of CSS media queries

Some layout concepts

Static Layout

  • In traditional Web design, the dimensions of all elements on the page are px, and the layout of the page is always the same as the original code layout, regardless of the browser size
  • Design method
    • PC side: Center the Layout, all styles use absolute width/height (PX) design a Layout, in the screen width and height adjustment using horizontal and vertical scroll bars to see the covered parts
    • Mobile: Create a separate mobile site, design a separate layout, and use a different domain name such as WAp. Or m., etc
  • Pros: This layout is easiest for designers and CSS writers, and there are no compatibility issues
  • Disadvantages: This layout does not behave differently depending on the user’s screen size. A fixed-pixel web page is the easiest way to match a fixed-pixel display, but this method is not fully compatible with the current web page creation method and requires some method to adapt to unknown devices

Liquid Layout

  • Liquid is a type of layout where the width of page elements is adjusted to fit the screen resolution, but the overall layout remains the same. Examples of Liquid are fence systems.
  • Use % percentages to define the width, and the height is mostly fixed with px. Can be adjusted according to the viewport and the real-time size of the parent element, as far as possible to adapt to various resolutions, usually with max-width/min-width and other attributes to control the size flow range to avoid too large or too small impact on reading (pictures, etc., the same is true, Width :100%; max-width :100%;
  • Layout features: When the screen resolution changes, the size of the elements on the page changes but the layout stays the same. This results in the elements not displaying properly if the screen is too large or too small
  • Pros: This layout was used in the early history of Web front-end development for PC screens of different sizes (when screen sizes didn’t vary much), and it’s also a common layout for mobile development
  • Disadvantages: Span of main problem is that if the screen size is too big, that the relative to its original design is too small or too large screen will not display properly, because the width use % percentage definition, but the height and size and so on are mostly use px to fixed, so under the big screen mobile phone display effect will become some of the elements on the page width is pulled very long, But the height and text size are still the same (i.e., these things can’t be “streamed”) and the display is very incongruous

Adaptive Layout

  • Features: Create multiple static layouts, each corresponding to a screen resolution range, use the @media media query to switch multiple layouts, and change the screen resolution to switch different static parts (the position of the page elements changes), but in each static layout the page elements do not change with the window size. You can think of adaptive layout as a family of static layouts
  • When screen resolution changes, the position of elements on the page changes but the size does not change
  • Design method: Use @media media query to switch different styles for devices of different sizes and media. With excellent response range design, it can give the best experience to devices in the suitable range

Responsive Layout

  • Responsive design goal is to ensure that a page on all terminals (various size of PC, mobile phones, watches, refrigerator Web browser, etc.) can show a satisfactory result, for CSS writers, on the implementation is not constrained by specific methods, but often it is a mix the fluid layout + flexible layout, tie-in media query technology used, Define layouts for different screen resolutions (responsive has almost become the standard for good page layouts)
  • Layout features: Each screen resolution has a layout style that changes the position and size of elements
  • Advantages: Suitable for PC and mobile terminal, if enough patience, perfect effect
  • Disadvantages:
    • Media queries are limited and can only be enumerated to accommodate the mainstream width and height
    • Matching enough screen sizes is a lot of work and requires multiple versions of the design

Flexible layout (REM/EM layout)

  • Rem is relative to the font size of an HTML element, while em is relative to its parent element (the non-font size attribute is relative to its own font size)
  • Using EM or REM is more flexible than % percentages, and allows for normal display of browser font resizing and zooming
  • Layout features: The dimensions of the elements surrounding the text are em/ REM, while the dimensions of the main sections of the page are still percentages or PX (same as “streaming layout” or “static/fixed layout”). The early browsers did not support scaling of the entire page, only allowing text within the page to be enlarged. Using em/ REM units in this case allows the element that wraps the text to scale as the text scales
  • The default font height for browsers is 16px, or 1em: 16px, but the ratio of 1:16 is not easy to calculate. In order to make the unit EM/REM more intuitive, CSS writers often set the page and node font to 62.5%. For example, when choosing rem control font, the font size of the root node HTML should be set first. Since the browser default font size is 16px * 62.5% = 10px, one rem is 10px for easy calculation
  • Another advantage of using EM/REM for sizing is that it is easier to indent, use font units such as padding or margin, and use browsers to set font sizes. }
  • The Flexible layout using REM units is also very popular on mobile terminals. Taobao’s Flexible makes REM layout popular, but the Flexible implementation also has some shortcomings. In addition, a variety of schemes have emerged to realize REM layout. Font-size :625%; } base values are used with JS to set the font size of the root element, or media queries are used to set the font size of the root element, etc

Traditional common layout

Document flow layout

This is the most basic layout, one by one in document order, with block elements occupying a row and inline elements sharing a row

Liquid layout

Float layout uses the float property to float elements out of the document flow

Locate the layout

Position is performed through the position property

The table layout

  • Directly use labels such as table layout, table layout automatically center vertically
  • Advantages of table: It is perfectly appropriate, appropriate and accurate to use table in some situations. For example, if you use table to make a table, if you cannot decide whether you should use table, please ask yourself some questions. If the answer is only “I guess… Maybe not “, then you shouldn’t use table
    • “Does the row or column information share an attribute? For example, each row displays one student’s information, and all students have a ‘name’ attribute.”
    • “If I change the order of these rows or columns, does it still make sense or have the same effect?”
    • “If you turn rows into columns or columns into rows, does it still make sense or have the same effect?”
  • In actual project development, it is not recommended to use table for layout for the following reasons:
    • Table takes up more bytes than other HTML tags (resulting in download delays and more traffic to the server)
    • Table blocks the rendering order of the browser rendering engine (delaying the generation of pages and making users wait longer). Table must be displayed after the page is fully loaded. Table is blank until the page is fully loaded, that is, div is displayed line by line. The page does not need to be fully loaded to be displayed as it loads
    • To display images in a table, you need to split a single logical image into multiple graphs (increase design complexity, increase page load time, increase HTTP sessions).
    • In some browsers, copying the text in the table can be problematic (annoying)
    • Table affects the effect of certain layout attributes within it (e.g. element height:100%) (limits page design freedom)
    • Once you learn CSS, you’ll find that using tables for page layouts becomes more cumbersome (taking the time to learn some CSS first will save you a lot of time later).
    • Table code can make readers crazy (not only does it not take advantage of CSS, but it can be confusing, especially when doing page changes or content extraction)
    • Tables are dead once designed, and it’s hard to make them look new with CSS (CSS ZEN GARDEN: www.csszengarden.com/)

What are the advantages of div + CSS over the Table layout? Revision is more convenient, as long as the CSS file page loading speed is faster, clear structure, simple page display, performance and structure separation is easy to optimize (SEO) search engine more friendly

Flex layout

What is the flex

2009 was an extraordinary year for the front end, with HTML5 finalized, ES5.1 released, and Flex. Flex is the acronym for Flexible Box. It is extremely simple to use and provides a simple, complete, and responsive layout for a variety of page layouts. As described in the specification, the Flexbox module provides an efficient layout method. You can adjust and allocate the relationship between elements and space intelligently and flexibly, even if you do not know the window size or unknown elements. The simple idea is that you can automatically adjust and calculate the size of elements in the container space

  • Flex is a new type of layout that you can use to achieve almost anything you want. Flex only supports IE 10+, so use it according to your project. Check out Can I use for compatibility

FFC (flex formatting context)

  • Flexbox layout defines a new formatting context, similar to the BLOCK Formatting Context (BFC), where everything is the same except layout and some details

    Note: Flexbox refers to display: flex; Or display: inline – flex; Display: flex; display: flex; The box

  • For example, display: flex; Or display: Inline-flex elements, like BFC, are not covered by floating elements, vertical margin collapse, etc
  • For a box with display: inline-flex set, the analogy is display: inline-box; Understood, it does not monopolize a row, but can set the width and height
  • Subtle differences with BFC
    • Flexbox does not support the pseudo-elements ::first-line and ::first-letter
    • Vertical-align has no effect on child elements in Flexbox
    • Float and clear properties have no effect on the child elements in Flexbox, nor do they take the child elements out of the document flow (but they do!).
    • Multi-column layouts (column-*) are also disabled in Flexbox, i.e. you cannot use multi-column layouts to arrange children under flexbox.
    • Children under Flexbox do not inherit the width of their parent container

Design expectations for the Flex box model

  • Good layout in any direction of flow (up, down, left and right)
  • Layouts can be arranged in reverse order or in any order
  • It can be arranged linearly along the main axis or in line breaks along the side axis
  • It can be flexibly scaled in any container
  • Child elements can be aligned along the main axis of the container or along the side axis of the container
  • The size of the child can be dynamically scaled along the main axis while ensuring the size of the parent side axis

The basic concept

  • There are two axes in the Flex container by default, the main axis and the vertical cross axis. This is the default setting, but you can change the vertical direction to the main axis and the horizontal direction to the cross axis

  • Each unit block in the container is called a Flex item, and each item occupies the main axis space (main size) and the cross-axis space (cross size).

    Note that the width is main size and the height is cross size, depending on the main axis. If the vertical direction is the main axis, the height of the project is main size

  • The writing-mode attribute can change the direction of the document flow, in which the main axis is vertical, but this scenario is rarely encountered in actual development, so there is no problem in using horizontal and vertical directions directly at the beginning of learning, and it is easier to understand

Using Flex layout

  • A Flex layout is implemented by specifying a container, and any container that is specified as a Flex layout can be laid out using Flex

    • Set to block elements such as divdisplay: flexOr set inline elements like spandisplay: inline-flexFlex layout is created! The elements that directly set display: flex or display: inline-flex are called flex containers, and the children inside are called Flex children
    • Note: The float, clear, and vertical-align attributes of the child elements are invalidated when the Flex layout is set
  • Flex layout attributes are divided into two sets: Wave action on the flex containers (here) is replaced by a “parent container, and those effects in flex items (here) is replaced by a” children “, detailed in the table below, regardless of the effect on the parent container, or role in a container, is controls the container, only the former control as a whole, the latter is the individual control

    Act on the parent container Acting child container
    flex-direction order
    flex-wrap flex-grow
    flex-flow flex-shrink
    justify-content flex-basis
    align-items flex
    align-content align-self
  • The flex-direction property applied to the parent container

    • Determines the orientation of the main axis (the default axis is horizontal, left to right), used to control the overall layout direction of the children, left to right or right to left, top to bottom or bottom to top. Compared to the DIRECTION property of CSS, there is flex
    // row: the default value, displayed as a row, is the horizontal flow direction of the current document (main axis), default is left to right. If the current horizontal document flow direction is RTL (for example, set Direction: RTL), it goes from right to left
    // row-reverse: displays as rows, but the orientation and row values are reversed
    // column: is displayed as a column in the vertical direction, starting from the top edge
    // column-reverse: displays as a column in a vertical direction, but the direction and column attribute values are reversed
    flex-direction: row | row-reverse | column | column-reverse;
    Copy the code

    flex-wrap

    • Determines whether the child container should be wrapped. By default, items are lined up on the main axis. Use flex-wrap to wrap items
    // nowrap: the default value, which indicates that a single line is displayed without newlines, that is, when the spindle size is fixed and there is not enough space, the item size is adjusted accordingly and does not squeeze into the next line
    // wrap: if the child spindles exceed the parent spindles, wrap the first line at the top
    // wrap-reverse: the width is not enough for a line feed, but starts from bottom up, i.e. the line feed goes to the top of the bottom child
    flex-wrap: nowrap | wrap | wrap-reverse;
    Copy the code

    flex-flow

    • Short for flex-direction and flex-wrap, row Nowrap is the default value for flex layout flow
    flex-flow: <flex-direction> || <flex-wrap>;
    Copy the code

    justify-content

    • CSS text-align, which determines the alignment and distribution of horizontal child containers, has an attribute value of justify for both ends
    • Illustration-content can be thought of as a distant cousin of text-align, except that the former controls horizontal alignment of flex elements plus distribution, while the latter controls horizontal alignment of inline elements
    // flex-start: the default value, the logical CSS property value, which depends on the direction of the document flow, is left aligned by default
    // flex-end: the logical CSS property value, which depends on the direction of the document flow and is right-aligned by default
    // center: represents a center alignment
    // space-between: indicates that both ends are aligned. Between means that the extra space is allocated only in the middle of the element
    // space-around: around means around, which means that each child container is surrounded by a non-interfering equal width of white space on both sides, resulting in a visual margin that is half the width of the middle
    // A space-instituted instituted is a evenly balanced, evenly body that visually matches the spacing between the sides of each child vessel
    
    justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
    Copy the code

    align-items

    • Items in align-items refers to the child container, so align-items refers to the vertical alignment of the child container relative to the parent container
    // stretch: the default value, the child container stretch, that is, if the child container is not set to height or set to auto, will take up the entire height of the parent container, if the child container is set to height, then render according to the set height, not stretch
    // flex-start: the logical CSS property value, which depends on the document flow direction, defaults to top alignment of the container
    // flex-end: the logical CSS property value, which depends on the direction of the document flow, defaults to bottom alignment of the container
    // Center: represents a vertical center alignment
    // baseline: all = child containers are aligned relative to the parent container's baseline (the lower edge of the letter X)
    align-items: stretch | flex-start | flex-end | center | baseline;
    Copy the code

    align-content

    • Align-content can be seen as a similar and opposite property to justify-content, which specifies the alignment and distribution of horizontal subcontainers, and align-content, which specifies the alignment and distribution of vertical subcontainers. The align-content property has no effect if all child containers have only one line
    • When flex-wrap is set to NowRAP, there is only one axis in the container, because the item does not wrap and does not generate multiple axes. When flex-wrap is set to WRAP, there may be multiple axes in the container, so you need to set the alignment between multiple axes
    // stretch: default value. Each row is stretched at the same proportion. If there are two rows, each row is stretched at 50%
    // flex-start: logical CSS property value, which depends on the direction of document flow. Default is top stack
    // flex-end: the logical CSS property value, which depends on the document flow direction, is stacked at the bottom by default
    // Center: represents the overall vertical center alignment
    // space-between: indicates that the upper and lower lines are aligned. And then we're left with the remaining space equally divided for each row
    // space-around: Each row of elements has independent, non-overlapping white space above and below it
    // space-instituted: Each row of elements will evenly split up and down
    align-content: stretch | flex-start | flex-end | center | space-between | space-around | space-evenly;
    Copy the code

  • The property order that acts on the child container

    • Defines the order in which children are arranged in the parent container. The smaller the value, the higher the order. The default value is 0
    order: <integer>; /* Integer value, default is 0 */
    Copy the code

    flex-grow

    • Grow means to expand the size of the child container. It defines the size of the item to be enlarged
    • Flex-grow does not support negative values. The default value is 0, which means it does not use the remaining space to expand. If flex-grow is greater than 0, the remaining space of the parent container is allocated
      1. The total amount of free space is 1
      2. If only one child has flex-grow set to 1) If the flex-grow value is less than 1, the expanded space is the total free space and the calculated ratio. 2) If the flex-grow value is greater than 1, all the free space is reserved
      3. If the sum of the flex-grow values is less than 1, then the total amount of space available for each child is the calculated value of the flex-grow ratio of the current element. If the sum of the flex-grow values is greater than 1, then the total amount of space available for each child is the calculated value of the flex-grow ratio of the current element. Then all remaining space is used, and the allocation ratio is the proportion of the flex-grow attribute value. If all child containers are set to Flex-grow: 1, it means that the remaining space is divided equally. If the flex-grow ratio is set to 1:2:1, the middle child takes up half of the space, and the remaining two elements are divided equally
      4. The flex-grow property is required if the space is insufficient and flex-wrap: nowrap is used when all items are arranged with the flex-basis value
    flex-grow: <number>; /* The value can be a decimal. The default value is 0 */
    Copy the code

    flex-shrink

    • Deal with the shrinkage ratio of individual elements when the parent container runs out of space
    • Flex-shrink does not support negative values. The default value is 1, which means that all child containers shrink by default. If it is set to 0, it does not shrink and keeps the original fit-Content width
    • The kernel of flex-shrink is similar to that of flex-grow, which is how space is used when there is enough space. Flex-grow is how space is shrunk when there is not enough space
    • For this property to take effect, the flex-wrap property of the parent container must be set to NowRAP
    • If only one child container has flex-Shrink set
      • If the flex-shrink value is less than 1, the size of the shrink is incomplete and some content overflows the parent container
      • If the flex-shrink value is greater than or equal to 1, the container shrinks completely to fill the parent container
    • If flex-shrink is set for multiple subcontainers
      • If the sum of the Flex-shrink values is less than 1, the shrink size is incomplete. The ratio of the shrink size of each element to the “complete shrink size” is the set Flex-shrink value
      • If the sum of the Flex-shrink values is greater than 1, the shrinkage is complete, and each element shrinks in the same proportion as the Flex-shrink value
      flex-shrink: <number>; The default value is 1 */
      Copy the code

    flex-basis

    • Defines the amount of spindle space that the project occupies before allocating excess space. Based on this property, the browser calculates whether the spindle has excess space
    • It can be set to the same value as the width or height attribute (such as 350px), and the project will take up a fixed space
    • Default value: auto, the original size of the item. The width and height of the item depend on the width and height
    • When the main axis is horizontal and flex-basis is set, the width value of the project is invalid. Flex stands for elastic, so it is not actually recommended to use the width property for flex children because it is not elastic enough
    • When there is not enough free space, the actual width of the child container is usually not the flex-basis set, because the Flex layout shrinks by default when there is not enough free space
    • When the flex-basis value is 0 %, the item is treated as zero size, even if the size is 140px, which is useless
    • When the flex-basis value is auto, the 100px will not be included in the remaining space, depending on the size set (such as 100px)
    • Flex-basis must be used in conjunction with flex-grow and Flex-shrink to be effective
    flex-basis: <length> | auto; /* default auto */
    Copy the code

    flex

    • The Flex attribute is a short form of flex-grow, flex-shrink, and Flex-basis
    • The second and third parameters (flex-shrink and flex-basis) are optional. The default value is 0 1 auto
    • Flex the default value is the same as flex: 0 1 auto;
    • Flex: none = flex: 0 0 auto;
    • Flex: auto = 1;
    flex: none | auto | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'>]// If flex is a non-negative number, the number is flex-grow, flex-shrink is 1, and flex-basis is 0%
    // Same as below
    .item {flex: 1; } .item { flex-grow:1;
         flex-shrink: 1;
         flex-basis: 0%;
    }
    
    // When flex is 0, the corresponding three values are 0 1 0%
    item {flex: 0; } .item { flex-grow:0;
         flex-shrink: 1;
         flex-basis: 0%;
    }
    
    // When flex is a length or percentage, the value is considered flex-basis, flex-grow is 1, and flex-shrink is 1
    // There is the following equivalent (note that 0% is a percentage and not a non-negative number)
    .item-1 {flex: 0%; } .item-1 {
         flex-grow: 1;
         flex-shrink: 1;
         flex-basis: 0%;
    }
    
    .item-2 {flex: 24px; } .item-2 {
         flex-grow: 1;
         flex-shrink: 1;
         flex-basis: 24px;
    }
    
    // If the value of flex is two non-negative digits, the value is regarded as flex-grow and flex-shrink respectively, and flex-basis is 0%, which is equivalent to the following:
    .item {flex: 2 3; } .item { flex-grow:2;
         flex-shrink: 3;
         flex-basis: 0%;
    }
    
    // When flex is a non-negative number and a length or percentage, it is treated as the value of flex-grow and flex-basis, respectively, and flex-shrink equals 1.
    .item {flex: 1132px; } .item { flex-grow:11;
         flex-shrink: 1;
         flex-basis: 32px;
    }
    Copy the code

    align-self

    • Align-self: align-self controls the vertical alignment of a single flex child. The align-items property on the parent container represents all flex children. Here’s self, a single individual
    • The only difference is that align-self has an auto (the default) that inherits the align-items property from the Flex container. The rest of the properties have the same meaning
  • Shrink and flex grow of the parent container and flex-wrap of the child container

    • When the flex – wrap to wrap | wrap – reverse and container width and width less than the parent container, flex – turns will work, children will be set according to the flex – turns the value of the amplifier (0 not enlarge)
    • When the flex – wrap to wrap | wrap – reverse, and the container width and more than one parent container width, first will wrap, wrap after each line of the right end are likely to have the remaining space (the last line contains items may be smaller than the first few lines are the remaining space will be bigger), Flex-grow takes effect. If all child containers in the current row have flex-grow of 0, the remaining space is reserved. If there is a child with a non-zero flex-grow in the current row, the remaining space will be occupied by the child with a non-zero flex-grow
    • When flex-wrap is nowRAP and the sum of the children is smaller than the width of the parent, flex-grow takes effect, and the children are enlarged according to the value set by flex-grow (0 items are not enlarged).
    • When flex-wrap is nowRAP and the child container width exceeds the parent container width, flex-shrink takes effect, and the child container shrinks according to the flex-shrink value (zero does not shrink). There is a special case, however, where flex-shrink is zero for all of the children in the row, which means that none of the children can shrink, and the annoying horizontal scroll bar occurs
    • In summary, it can be seen that in all cases only one flex-shrink and one flex-grow work at the same time. The reason why flex-grow works is very simple: if there is enough space, flex-grow works, and if there is less space, flex-shrink works. Flex, of course – the value of the wrap to wrap | wrap – reverse that can wrap, since can wrap, usually always enough space, flex – the shrink of course won’t work

conclusion

Flexbox layouts work best for components and small-scale layouts of applications (one-dimensional), while Grid layouts work best for larger-scale layouts (two-dimensional)

The grid layout

  • A Grid layout, also known as a “grid layout,” allows for a two-dimensional layout, similar to the old Table layout, and can rely on media queries to define new layouts for different contexts. (Flex layouts, while powerful, are one-dimensional)
  • Unlike table layouts, grid layouts do not require the use of specific tag layouts in HTML, all of the layout is done in CSS, and you can define the grid grid at will
  • Grid layout can also get rid of now existing in the layout of the document flow restriction, the structure is to be arranged according to the design draft from above, it also means that can freely change the position of page elements, the most suitable for the layout of the different breakpoint location to realize the need, but no longer need to worry about the structure of the HTML in response to the design

A grid layout without HTML structure helps to manage or change the layout using techniques such as fluid, reordering, and so on. By combining the media query properties of CSS, you can control the grid layout containers and their child elements, using the layout of the page to adjust the display style and positioning of elements according to different devices and available space, without changing the essence of the document structure

Browser compatibility

For details, see: Can I use

Some concepts in the Grid

See CSS Grid layout: What is a Grid layout

Grid Lines

  • Grid lines are grouped into grids, which are the horizontal and vertical boundaries of a grid. A grid line exists on either side of a row or column, and its number or defined grid line name can be referenced

Grid Track

  • A grid track is a space between two adjacent grid lines, just like rows or columns in a table. All grid tracks are divided into grid columns and grid rows. Each grid track can be set to a size to control the width or height

Grid cells

  • A grid cell is the space between four grid lines, so it’s the smallest unit, like a cell in a table

Grid Area

  • A grid region is a space made up of any four grid lines, so it may contain one or more cells, equivalent to the region behind the combined cells in the table

Using a Grid Layout

  • Using a grid layout is simple, using the display attribute to set the property value to grid or inline-grid or subGrid (the parent element is grid and inherits the row and column sizes of the parent element)
  • All the child elements in the grid container automatically become grid items, and then set the size of grid-template-columns and grid-template-rows. Grid-template-columns specifies the number of columns in the grid table. If grid-template-columns is not set, there will be only one column, 100% of the width of the parent element
<div class="grid-container">
    <div class="item item1">1</div>
    <div class="item item2">2</div>
    <div class="item item3">3</div>
    <div class="item item4">4</div>
    <div class="item item5">5</div>
    <div class="item item6">6</div>
</div>

Grid-template-row is not set to grid-template-columns
.grid-container{
     display: grid;
     grid-template-rows: 50px 80px 100px;
     background: pink;
}
.item{
     border: 2px solid palegoldenrod;
     color: #fff;
     text-align: center;
     font-size: 20px;
}
Copy the code

Note: The column, float, clear, vertical-align attributes are invalid when the element has a grid layout

  • Grid-template-row specifies the height of each column. Grid-template-row specifies the height of each column. Grid-template-row specifies the height of each column. Although four grid-template-rows are set, only the first two values take effect because there are only two rows
.grid-container {
      padding: 20px;
      display: grid;
      grid-template-rows: 50px 100px 60px 80px;
      grid-template-columns: 50px 40px 100px 80px;
      background: pink;
}
.item {
      border: 2px solid palegoldenrod;
     color: #fff;
}
Copy the code

  • You can set the width of each column as flex does, using a new unit: fr

    CSS fr unit is an adaptive, fr unit is used in the distribution of the remaining space in the series of the length value, if already specified the parts, then the rest of the space according to their respective digital proportional distribution fr was calculated based on grid container space available (flex), so if you need to can be used mixed with other units

grid-template-columns: 1fr 1fr 2fr;
Copy the code

Minimum and maximum size of a row or column

  • The minmax() function creates the minimum maximum size of the row or column. The first parameter defines the minimum size of the grid track, and the second parameter defines the maximum size of the grid track
.grid-container {
     padding: 20px;
     display: grid;
     grid-template-rows: minmax(100px,200px) minmax(50px,200px);
     grid-template-columns: 1fr 1fr 2fr;
     background: pink;
     height: 300px;
}
Copy the code
  • Set the first row height to minmax(100px,200px), the second row height to Minmax (50px,200px), and the total container height to 300px.
    • Check whether the total height is less than the sum of the maximum heights in the first column and the maximum heights in the second column. If it is greater than the sum of the maximum heights, the heights in the first column and the second column are the maximum values; if it is less than the sum of the minimum values, the heights in the first column and the second column are the minimum values
    • Then here we start with a total height of 300px – a minimum height of 100px in the first column – a minimum height of 50px in the second column = 150px
    • Height of the first column: minimum height of the first column 100px + 150px/2 = 175px;
    • Second column height: minimum height of the second column 50px + 150px/2 = 125px;

Repeat rows or columns

  • The repeat() property creates repeating grid tracks, which is good for creating grid items of equal size and multiple grid items
  • Repeat () takes two parameters: the first defines how many times the grid track should be repeated, and the second defines the size of each track
.grid-container{
    padding: 20px;
    display: grid;
    grid-template-columns: repeat(2,100px);
    grid-template-rows: repeat(3,100px);
    background: pink;
}
Copy the code

spacing

  • Grid-column-gap: Creates the distance between columns
  • Grid-row-gap: the distance between rows
  • Grid-gap: short form of grid-row-gap and grid-column-gap properties
 .grid-container{
    padding: 20px;
    display: grid;
    grid-template-columns: repeat(2,100px);
    grid-template-rows: repeat(3,100px);
    grid-column-gap: 50px;
    grid-row-gap: 15px;
    background: pink;
}
Copy the code

Locate grid Items by grid lines

  • Grid Items can be located by table line rows or columns
  • Grid-row: short for grid-row-start and grid-row-end
  • Grid-column: short forms of grid-column-start and grid-column-end
  • Grid-row-start and grid-column-start values are specified if only one value is provided
  • If two values are provided, the first value is grid-row-start or grid-column-start, and the second value is grid-row-end or grid-column-end. The two values must be separated by a slash (/)
grid-row: 2; 
grid-column: 3 / 4;
Copy the code
  • Grid-area: grid-row-start grid-column-start Grid-row-end Grid-column-end Grid-area: grid-row-start grid-column-start grid-row-end grid-column-end
grid-area: 2 / 2 / 3 / 3;
Copy the code
.grid-container {
    padding: 20px;
    display: grid;
    grid-template-columns: repeat(2,100px);
    grid-template-rows: repeat(3,100px);
    grid-column-gap: 50px;
    grid-row-gap: 15px;
    background: pink;
}
.item {
    border: 2px solid palegoldenrod;
    color: #fff;
    text-align: center;
    font-size: 20px;
}
.item1 {
    grid-row-start: 2;
    grid-row-end: 3;
    grid-column-start: 2;
    grid-column-end: 3;
    background: #fffa90;
    color: #000;
}
Copy the code

Merge cell row and merge cell column

  • This is the same as merging cell rows/columns in Excel (need to be set in grid Item)
  • Grid-row and grid-column abbreviations can also be used, with span followed by a number indicating how many columns or rows are merged, and/starting with the row/column
.grid-container {
      padding: 20px;
      display: grid;
      grid-template-columns: repeat(4,100px);
      grid-template-rows: repeat(3,100px);
      grid-column-gap: 50px;
      grid-row-gap: 15px;
      background: pink;

}
.item {
      border: 2px solid palegoldenrod;
      color: #fff;
      text-align: center;
      font-size: 20px;
}
.item1 {
      grid-column-start: 1;
      grid-column-end: 3;
      grid-row-start: 2;
      grid-row-end: 4;
}

/ / or
// .item1 {
// grid-row: 2 / span 3;
// grid-column: span 2;
/ /}
Copy the code

Custom grid line name

  • In a grid, you can customize the name of the grid lines and then use the defined grid lines for layout,[col1-start]The gridline name must be used[]Enclose the
  • The text and guides in the image below were added behind the scenes

Name and locate grid items through grid areas

What is a grid area

  • Grid-area is a logical space, which is mainly used to place one or more grid cells. It is a grid Track organized by four grid lines, one on each side of the grid area, and four intersecting sides. A grid region is a grid space interlaced with four grid lines, which may be a grid cell or multiple grid cells

Defining grid areas

  • There are two ways to define Grid areas in CSS Grid Layout. One is through Grid lines and the other is through grid-template-areas

Grid lines define grid areas

  • First, grid lines are explicitly defined by grid-template-columns and grid-template-rows, or even implicitly created by the browser. Then, grid-area is used to form a grid-line interlacing area, which is the grid area in question
  • When using the grid-area attribute to call a gridline, follow the following rulesgrid-area: row-start/ column-start / row-end / column-end

Grid-template-areas define grid areas

  • In the CSS Grid Layout, the grid-template-Areas attribute can be used to define the name of the Grid area. The grid-area attribute can be used to specify the elements that need to be placed in the corresponding Grid area
  • The same name can be used for overlapping regions, and a dot can be used for empty orbital regions. To represent the
<div class="grid-container">
    <div class="header ">header</div>
    <div class="content ">content</div>
    <div class="sidebar ">sidebar</div>
    <div class="footer ">footer</div>
</div>
.grid-container {
    text-align: center;
    padding: 20px;
   display: grid;
   grid-column-gap: 5px;
   grid-row-gap: 5px;
   background: pink;
   grid-template-areas: "header header header header header"
                        "sidebar content content content content"
                        "footer footer footer footer footer";
   grid-template-rows: 50px 150px 50px;
   grid-template-columns: 200px 200px 200px;
}
.header { grid-area:header; background: #fff}
.content { grid-area: content; background: #fffa90}
.sidebar { grid-area: sidebar; background: #5bc0de}
.footer { grid-area: footer; background: #ffff00}
Copy the code

  • The layout has the advantage of not setting the height (the parent container and grid-template-rows values, or grid-template-rows set to auto, are the same height as the content and will be adaptive to the height within them), as in

Rem layout

What is a rem

  • Rem and EM are easily confused. In fact, they are both units of CSS and relative units. Rem was introduced in CSS3 first, so let’s know about EM before introducing REM

Em represents the font size of the parent element when used as a unit of font size. Em represents its own font size (MDN) when used as a unit of other attributes

  • Em can make pages more flexible and robust. Em seems to have more tension than dead PX values written all over the place. Changing the font size of the parent element is proportionally different, which seems to promise endless possibilities
  • Some people have proposed using EM to make flexible layout pages, but the complexity of the calculation has been criticized, and there is even a special px and EM calculator, the em values corresponding to different node pixel values

  • The downside of em’s flexible layout is that it is a matter of timing. If a node’s font size changes, its descendants have to be recalculated
  • rem

When REM is applied to non-root elements, the font size relative to the root element; When REM is applied to the font size of the root element, relative to its initial font size — MDN

/* Applies to the root element, relative to the original size (16px), so the HTML font size is 32px*/
html {font-size: 2rem}

/* applies to non-root elements, relative to the root element font size, so 64px */
p {font-size: 2rem}
Copy the code
  • Rem and EM each have their own advantages. I always think that there is no right or wrong technology, only suitable or not. Personally, EM is born for font and line height, sometimes the child element font should be relative to parent element, element line height should be relative to font size; The advantage of REM is a unified frame of reference

Rem layout principles

The core of REM layout is setting the font size of the root HTML element. The essence of REM layout, in my opinion, is proportional scaling, generally based on width

Suppose that the width of the screen is divided evenly into 100 parts. The width of each part is denoted by x, x = the width of the screen divided by 100. If x is used as a unit, the number before x represents the percentage of the screen width. Unfortunately CSS does not have such units. Fortunately CSS does have REM. Rem is the bridge through which the magic X can be achieved

div { width: 50x } /* 50% of the screen width */
Copy the code

If the child element sets the REM unit property, the actual size of the child element can be changed by changing the font size of the HTML element

html { font-size: 16px }
div { width: 2rem } /* 32px*/

html { font-size: 32px }
div { width: 2rem } /*64px*/
Copy the code

If the font size of an HTML element is equal to 1/100 of the screen width, 1rem is equivalent to 1x

html { fons-size: width / 100 }
div { width: 50rem } /* 50rem = 50x = 50% of the screen width */
Copy the code

How do I always keep an HTML font size equal to 1% of the screen width? This can be set using JS, usually in page DOM Ready, resize, and screen rotation

document.documentElement.style.fontSize = document.documentElement.clientWidth / 100 + 'px';
Copy the code

How do YOU convert the value in pixels captured in UE (UE stands for User Experience) to a value in REM? Let’s assume that the UE diagram is 640px and that the width of an element in the UE diagram is 100px, which according to the formula is 100/640 * 100 = 15.625

div { width: 15.625rem }
Copy the code

The table below shows the width of the elements in the UE diagram at scaleThe table below shows the calculated values of elements at different screen widthsAs can be seen from the above figure, the width of elements on both sides of the UE diagram is the same as the width of the screen

The above calculation process is a little tedious, which can be simplified by preprocessing function. The following is the example of SASS, similar to less

$ue-width: 640; /* The width of the ue graph */
@function px2rem($px) {@return #{$px/$ue-width*100}rem;
}

div {
    width: px2rem(100);
}
Copy the code

In fact, with postCSS, this process should be put in PostCSS, source code below

div { width: 100px2rem }

// Postcss handles the px2rem unit as follows
p { width: 15.625rem }
Copy the code

On mobile devices, to prevent blurring due to a lack of pixels on an hd screen, you get a design 640px (320px on the iphone5) or double the size of 750px (375px on the iphone6), double the size depending on the width of the device. What size do you want to set in your CSS at development time? How to adapt a design draft to different models?

  • The best solution is to measure the size of an element, image, or text in Photoshop or any other tool and write it directly into the code
    • Based on this, SCSS can be used to provide a range of basic support
    • In order to facilitate calculation, the page is divided into 10 blocks, according to the mapping relationship only need to calculate the amount of a certain element in the page ($REM), combined with the size of the HTML font size, can set the correct element size on the page
      width: px2rem(200);
      
      /* Width of mobile page design draft */
      $design-width: 750;
      /* DPR reference value of mobile terminal page design draft */
      $design-dpr: 2;
      /* Split the mobile page into 10 pieces */
      $blocks: 10;
      /* Scale the supported minimum width of the device */
      $min-device-width: 320px;
      /* Scale the maximum width of supported devices */
      $max-device-width: 540px;
      
      /* rem = px; /* rem = px; /* rem = px; $rem is $px corresponding accounts for how many pieces of $p $rem -- -- -- -- -- -- -- -- -- -- -- -- -- = = = -- -- -- -- -- -- -- -- -- -- -- -- $$blocks design - width * /
      
      /* Unit px is converted to rem */
      @function px2rem($px) {@return #{$px / $design-width * $blocks}rem;
      }
      
      /* Units of rem are converted to px, which can be used to quickly calculate the original px */ based on rem units
      @function rem2px($rem) {@return #{$rem / $blocks * $design-width}px;
      }
      
      // In the corresponding JS file
      // In the corresponding JS file
      var docElem = document.documentElement,
          metaElem = document.querySelector('meta[name="viewport"]'),
          dpr = window.devicePixelRatio || 1.// Divide the page into 10 pieces
          blocks = 10.// The minimum width to limit
          defaultMinWidth = 320.// The maximum width that needs to be restricted
          defaultMaxWidth = 540.// Calculate the base value
          calcMaxWidth = 9999999;
      
      // Set the docElem font size
      function setFontSize() {
          var clientWidth = docElem.clientWidth;
          clientWidth = Math.max(clientWidth, defaultMinWidth * dpr)
          // Adjust the calculation base value
          if (calcMaxWidth === defaultMaxWidth) {
              clientWidth = Math.min(clientWidth, defaultMaxWidth * dpr);
          }
          docElem.style.fontSize = clientWidth / blocks + 'px';
      }
      setFontSize();
      window.addEventListener(window.orientationchange ? 'orientationchange' : 'resize', setFontSize, false);
      Copy the code

In REM layout, viewport scale is commonly used. The viewport scale is very simple, and the scale in the meta tag is directly changed. If the DPR is 3, the scale is as follows. However, zooming is not well supported on some Android devices, and other tests need to be done (tested on some models currently in use, it should not be complete). Meanwhile, the DPR of the final calculation is put into HTML for CSS to do some special adaptation

// Most Android models with DPR below 2 do not recognize scale and need to be set not to scale
if (navigator.appVersion.match(/android/gi) && dpr <= 2) {
    dpr = 1;
}

setScale(dpr);
// After scale is set for enterprise QQ, scale cannot be fully recognized (at this time clientWidth is doubled without being affected by scaling), so no scaling should be set
if (navigator.appVersion.match(/qq\//gi) && docElem.clientWidth <= 360) {
    dpr = 1;
    setScale(dpr);
}
docElem.setAttribute('data-dpr', dpr);
// Set the zoom
function setScale(dpr) {
    metaElem.setAttribute('content'.'initial-scale=' + 1 / dpr + ',maximum-scale=' + 1 / dpr + ',minimum-scale=' + 1 / dpr + ',user-scalable=no');
}
Copy the code

Set the maximum and minimum width of the container

  • Above, as you stretch, the content area gets bigger and bigger, and the size of each element gets bigger and bigger, and the minimum width has been processed
  • There are two key points to control the scale: the size base and the container width (the size base is in data-Content-max and the container width is in the body tag)
  • For matching control in JS, note that since the viewport has been scaled, clientWidth will be larger than the device width, remember to double it with DPR
  • If you limit only the computed base value, but the container does not (remove the attribute from the body tag), you can achieve some sort of streaming effect (alternative)
<! DOCTYPE HTML > < HTML > <head> <title>REM layout </title> <meta charset=" UTF-8 "> <meta lang=" zh-cn "> <meta name="viewport" data-content-max content="width=device-width,initial-scale=1,user-scalable=no"> <link rel="stylesheet" href="./rem.css"> <script SRC ="./rem.js"></script> </head> <body data-content-max> <section class="container"> // js // The minimum width to limit var DefaultMinWidth = 320, defaultMaxWidth = 540, calcMaxWidth = 9999999; if (metaElem.getAttribute('data-content-max') ! == null) { calcMaxWidth = defaultMaxWidth; }... Function setFontSize() {var clientWidth = docelem.clientWidth; clientWidth = Math.max(clientWidth, If (calcMaxWidth === defaultMaxWidth) {clientWidth = math.min (clientWidth, defaultMaxWidth * dpr); } docElem.style.fontSize = clientWidth / blocks + 'px'; } // In CSS, a simple call to the core method has been removed from the HTML {@include root-width(); } /* HTML root width definition */ @mixin root-width() {body {@include container-min-width(); &[data-content-max] { @include container-max-width(); } / / [data-dpr="1"] body {min-width: $min-device-width; }} / / @mixin container-min-width() {margin-right: auto; margin-left: auto; min-width: $min-device-width; @media (-webkit-device-pixel-ratio: 2) { min-width: $min-device-width * 2; } @media (-webkit-device-pixel-ratio: 3) { min-width: $min-device-width * 3; @mixin container-max-width() {margin-right: auto; margin-right: auto; margin-right: auto; margin-right: auto; margin-left: auto; max-width: $max-device-width; @media (-webkit-device-pixel-ratio: 2) { max-width: $max-device-width * 2; } @media (-webkit-device-pixel-ratio: 3) { max-width: $max-device-width * 3; }}Copy the code

Whether text size is in REM units

  • Sometimes I don’t want the text to get smaller on the Retina screen, and I also want to see more text on the larger screen, and most font files now have some dot matrix sizes, usually 16px and 24px, so I don’t want 13px and 15px. You can choose to use px or rem units if you are not too strict
/* Set the font size, do not use rem units, according to the DPR value piecewise */
@mixin font-size($fontSize) {
    font-size: $fontSize / $design-dpr;

    [data-dpr="2"] & {
        font-size: $fontSize / $design-dpr * 2;
    }

    [data-dpr="3"] & {
        font-size: $fontSize / $design-dpr * 3;
    }
}
@include font-size(30px);
Copy the code

Rem is not a silver bullet

  • Rem is a way to realize elastic layout. Elastic layout can be regarded as one of responsive layout, but responsive layout is not elastic layout. Elastic layout emphasizes equal scale and 100% restoration. Responsive layouts emphasize different displays for different screens, such as media queries
  • It seems that general content websites are not suitable to use REM, because users with large screens can choose whether to use larger font or more content. Once rem is used, users’ freedom is deprived. For example, Baidu Knows and Baidu Experience do not use REM layout. Rem is suitable for some apps, ICONS and pictures, such as Taobao and activity pages, because the size of ICONS cannot be increased when the font is increased
  • Rem can achieve 100% reduction degree, but at the same time, REM production costs are also higher, and there are some problems with using REM, as listed below
    • First of all, there’s the problem of fonts, because you can’t use REM for font size, so you can’t use REM for font size; Setting the font size for the root element affects all elements that do not have a font size, because font sizes are inherited and it does not make sense for each element to display the set font size
    • It is possible to make font corrections on the body, such as setting the body font size to 16px, but the user’s Settings will not be valid if the user sets a larger font, such as setting it to the user’s default font size
    html { fons-size: width / 100 }
    body { font-size: 16px }
    Copy the code
    • So how is the font size responsive? This can be done by changing the size of the body font, and all font size Settings are in EM units, because only EM can be synchronized. Of course, it is reasonable and good to have the same font size on different screens, so it is up to you to decide
    @media screen and (min-width: 320px) {
      body {font-size: 16px}
    }
    @media screen and (min-width: 481px) and (max-width:640px) {
      body {font-size: 18px}
    }
    @media screen and (min-width: 641px) {
      body {font-size: 20px}
    }
    
    div {font-size: 1.2em}
    div a {font-size: 1.2em}
    Copy the code
    • What if the page is too wide when the user browses on the PC? Generally, a maximum width is set. If the width is greater than this, the page is centered with white space on both sides. Set the width of the body to 100rem and center it horizontally
    var clientWidth = document.documentElement.clientWidth;
    clientWidth = clientWidth < 780 ? clientWidth : 780;
    document.documentElement.style.fontSize = clientWidth / 100 + 'px';
    
    body {
      margin: auto;
      width: 100rem
    }
    Copy the code
    • What if the user disables JS? In fact, this kind of users really not much, or give up…
    // A noscript tag can be added to prompt the user<noscript> Enable JavaScript for a better experience </noscript>// Add a default font size of 320 to the HTML to make the page display
    html {fons-size: 3.2px}
    
    // If you want a better experience, add media query
    @media screen and (min-width: 320px) {
      html {font-size: 3.2px}
    }
    @media screen and (min-width: 481px) and (max-width:640px) {
      html {font-size: 4.8px}
    }
    @media screen and (min-width: 641px) {
      html {font-size: 6.4px}
    }
    Copy the code
  • Rem is not a silver bullet, there are no silver bullets in the world, every solution has advantages and disadvantages, learning to choose and compromise is king
  • Rem can only scale content, but does not solve the distortion of non-vector resources such as image enlargement

Rem layout scheme

The vm layout

  • CSS3 brings REM as well as VW and VH

Vw: 1/100 of the viewport width; Vh: 1/100 of the viewport height — MDN

  • REM layout uses JS to dynamically set the FONT size of HTML, which can cause page jitter
  • A relatively new VW layout can be considered without JS. Although it is not supported until above iOS 8 and Android 4.4 on mobile terminals, it is still worth using. If compatibility is required, you can try viewport-units-BuggyFill
  • With VW, rem can be completely bypassed. The following two schemes are equivalent
/* REM */
html { fons-size: width / 100 }
div { width: 15.625rem }

/* vw solution */
div { width: 15.625vw }
Copy the code
  • When elastic layout is used, the minimum and maximum widths are generally limited. For example, when viewing the page on PC, VW is powerless. Vw calculates according to the width of the device, so it cannot set the maximum and minimum widths of containers. Rem can easily solve this problem by controlling the maximum font size of the HTML root element

Rem + VW layout

  • Rem is introduced to solve the problem that the maximum and minimum width cannot be set for pure VM layout
  • By setting the font size of the HTML root element to VW and the maximum and minimum pixel px values, rem can be directly used as a unit in other CSS code, which is super easy to call
html {
    @include root-font-size();
}
line-height: px2rem(300);
Copy the code
  • The implementation in SCSS also defines a mapping relationship and blocks the page width (just to prevent the value from being too large).
  • In this case, the max-width value is used directly because vw is used and the window is not scaled, whereas in the page tag (HTML and body), the attribute simply indicates whether the width is limited
  • The “streaming effect” can also be achieved if only the calculation of the reference value and the container width are limited.
html {
    @include root-font-size();
}
line-height: px2rem(300);
/* Width of mobile page design draft */
$design-width: 750;
/* DPR reference value of mobile terminal page design draft */
$design-dpr: 2;
/* Split the mobile page into 10 pieces */
$blocks: 10;
/* Scale the supported minimum width of the device */
$min-device-width: 320px;
/* Scale the maximum width of supported devices */
$max-device-width: 540px;
/* rem = 1rem; /* rem = 1rem; $rem is $px corresponding accounts for how many pieces of $p $rem -- -- -- -- -- -- -- -- -- -- -- -- -- = = = -- -- -- -- -- -- -- -- -- -- -- -- $$blocks design - width * /
/* The font-size definition of the HTML root element, which simply divides the page into $blocks for easy calculation */
@mixin root-font-size() {
    font-size: 100vw / $blocks;

    body {
        @include container-min-width();
    }

    /* Minimum width definition */
    @media screen and (max-width: $min-device-width) {
        font-size: $min-device-width / $blocks;
    }

    /* Maximum width definition */&[data-content-max] { body[data-content-max] { @include container-max-width(); } @media screen and (min-width: $max-device-width) { font-size: $max-device-width / $blocks; }}}/* Sets the minimum width of the container to be stretched */
@mixin container-min-width() {
    margin-right: auto;
    margin-left: auto;
    min-width: $min-device-width;
}
/* Sets the maximum width of the container to be stretched */
@mixin container-max-width(){ margin-right: auto; margin-left: auto; max-width: $max-device-width; } <! DOCTYPE HTML > < HTML data-content-max> <head> <title>VW-REM layout </title> <meta charset=" UTF-8 "> <meta lang=" zh-cn "> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"> <link rel="stylesheet" href="./vw-rem.css"> </head>Copy the code

contrast

  • Each scheme can ensure certain adaptation in different models
  • In general, consider using REM layouts directly, since REM uses JS to dynamically set the font size of the HTML
  • However, Scale is not friendly to Android models, and VW can be used for the extreme
  • Pure VW layout does not support setting the maximum and minimum width and height of containers. If this function is required, REM + VW layout is used
rem vm rem + vm
Minimum container width support Does not support support
Maximum container width support Does not support support
Hd device 1px border support support support
Fixed aspect ratio of container support support support
advantages 1. Good compatibility of REM units

2, support hd device 1px border can be directly written 1px in the previous way
No need to introduce JS

2. The usage of VW is relatively standard
With the vm
disadvantages 1, use javascript to set the HTML font size

2. Use Scale to set viewport zoom to support 1px on HD devices, but scale is not very compatible on Android

3. The use of REM is not quite standard, with some hack features
1. Vw units are not compatible on older models

2. In order to support 1px for HD devices, more complex SCSS mixins are used, occupying :after pseudo-classes, which will generate more code
With the vm

use

  • The usual approach is to bring in common base code and call it in business code
  • The data-content-max parameter can be configured in an HTML file to limit the maximum and minimum width
  • These values can also be customized in the basic part of SCSS (in case of REM layout, these values need to be synchronized in the rem.js file)
/* Width of mobile page design draft */
$design-width: 750;
/* DPR reference value of mobile terminal page design draft */
$design-dpr: 2;
/* Split the mobile page into 10 pieces */
$blocks: 10;
/* Scale the supported minimum width of the device */
$min-device-width: 320px;
/* Scale the maximum width of supported devices */
$max-device-width: 540px;
Copy the code