“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Special statement: The original is not easy, shall not be reproduced without authorization or plagiarism, if you need to reprint can contact the author authorization

preface

Recently, some readers have quietly discovered my personal website, and every single one of them uses words like surprise and wonder. Yes, I used a lot of CSS to illustrate the artistic beauty of playing with CSS. Even if some application scenarios lack of JS support, the author can also play CSS with ease and ease, the entire site source CSS occupy about 60% of the component, many effects are not to show off but want to tell you the importance of CSS and practical. Therefore, I want to share some common and special layout techniques for pure CSS layout that you may not know and are super practical.

The development of each page is inseparable from the layout and typesetting, based on good layout and typesetting to lay the foundation, in order to make the subsequent development more smoothly. Of course, can not stay in the IExplorer era that limited thinking, can not solve the layout layout with JS 😂. Today is different from the past, modern CSS attributes can be better to achieve a variety of layout quickly, save more time to fish 😉.

However, according to the author’s current understanding of the situation, most students even in the case of compatibility with IExplorer or follow the CSS+JS way to complete some common or special layout layout. From the perspective of the positioning of the three muskers in the FRONT end of HTML/CSS/JS, HTML maps the structure of the page, CSS maps the performance of the page, AND JS maps the behavior of the page.

Layout Layout refers to the process of adjusting the position, size and other attributes of visual information elements such as graphics, text, images and media on the page layout to make the page layout become organized. Most students think that layout is just a few reasonable CSS attributes thrown together, but most of the time, even if the implementation will have flaws, it is possible to use JS to intervene.

From the characteristics of layout layout can be known that it belongs to the category of performance, so the author believes that most layout layout can be completed using pure CSS, without JS intervention.

This article follows the principle of using CSS first to achieve what can be achieved with CSS, and shows you how the author skillfully used a variety of pure CSS development techniques to achieve some common and special layout. Therefore, I suggest that you carefully read the following content, absolutely let you receive and surprise.

If you are not interested in CSS, I suggest you try the following websites. I believe you will read this article carefully.

  • Personal website: Temporary supportPCBrowse, reject supportIExplorer
  • Special album: Temporary supportPCBrowse, reject supportIExplorer

attribute

Before entering the theme, the author summarizes some essential attributes of layout, which can quickly build the overall effect, and then modify it with some common selectors to achieve the perfect effect. It may seem simple, but it may not be completely harnessed.

The required properties are geometric properties that are used to declare location and size.

  • Liquid layout:float
  • Locate the layout:position/left/right/top/bottom/z-index
  • Elastic layout:display:flex/inline-flex,Flex series properties
  • The box model:box-sizing/margin/padding/border/width/height

Selectors are derived from a large number of CSS modules. Without a special way to remember the functions of these selectors, it is difficult to make the most of them.

According to the function of the selector, the author divided eight categories, each category of the selector can be combined with each other in an application scenario, remember these categories of selector, I believe that the selector can play the maximum role, but also can easily apply it to some common or special layout.

The layout may be applied only to certain selectors, but it does not prevent you from memorizing it in the following ways. Selectors, as an important part of CSS, have more gameplay than attribute combinations.

Base selector

The selector The alias instructions version The commonly used
tag Label selector Of specified typeThe label 1 Square root
#id The ID selector identity-specificThe label 1 Square root
.class Class selectors That specifies the class nameThe label 1 Square root
* Wildcard selector Of all kindsThe label 2 Square root

Hierarchical selector

The selector The alias instructions version The commonly used
elemP elemC Descendant selector Elements of theDescendant elements 1 Square root
elemP>elemC Child selector Elements of theChild elements 2 Square root
elem1+elem2 Adjacent sibling selector Element adjacentsibling 2 Square root
elem1~elem2 Universal sibling selector After elementsibling 3 Square root

Collection selector

The selector The alias instructions version The commonly used
elem1,elem2 Union selectors Multiple specifiedThe element 1 Square root
elem.class Intersection selector That specifies the class nameThe element 1 Square root

Conditional selector

The selector instructions version The commonly used
:lang That specifies the markup languageThe element 2 x
:dir() Specifying the direction of writingThe element 4 x
:has Containing the specified elementThe element 4 x
:is conditionalThe element 4 x
:not Not specifiedThe element 4 Square root
:where conditionalThe element 4 x
:scope The specifiedThe elementAs a reference point 4 x
:any-link All containhreftheLink element 4 x
:local-link All containhrefAnd belonging to the absolute addressLink element 4 x

State selector

The selector instructions version The commonly used
:active mouseactivatedThe element 1 x
:hover mousehoverThe element 1 Square root
:link Without access toLink element 1 x
:visited Have access to theLink element 1 x
:target Of the current anchorThe element 3 x
:focus Input-focusedThe form elements 2 Square root
:required Enter mandatoryThe form elements 3 Square root
:valid Input legalThe form elements 3 Square root
:invalid Invalid inputThe form elements 3 Square root
:in-range Within the input rangeThe form elements 3 x
:out-of-range Outside the input rangeThe form elements 3 x
:checked SelectedThe form elements 3 Square root
:optional Options OptionalThe form elements 3 x
:enabled event-enabledThe form elements 3 x
:disabled Event-disabledThe form elements 3 Square root
:read-only read-onlyThe form elements 3 x
:read-write Readable and writableThe form elements 3 x
:target-within Where the internal anchor element is activeThe element 4 x
:focus-within The internal form element is in focusThe element 4 Square root
:focus-visible Input-focusedThe form elements 4 x
:blank The input is emptyThe form elements 4 x
:user-invalid Input legalThe form elements 4 x
:indeterminate The options are openThe form elements 4 x
:placeholder-shown Placeholder displayThe form elements 4 Square root
:current() Browse theThe element 4 x
:past() Have been browsingThe element 4 x
:future() Not browseThe element 4 x
:playing Starting to playMedia elements 4 x
:paused PausedMedia elements 4 x

Structure selector

The selector instructions version The commonly used
:root The documentThe root element 3 x
:empty Having no childrenThe element 3 Square root
:nth-child(n) Element in which the sequential index is specifiedThe element 3 Square root
:nth-last-child(n) Element in which the reverse index is specifiedThe element 3 x
:first-child The leading element in theThe element 2 Square root
:last-child The tail in the elementThe element 3 Square root
:only-child The parent element has only that element’sThe element 3 Square root
:nth-of-type(n) Label that specifies the order indexThe label 3 Square root
:nth-last-of-type(n) Label that specifies the reverse indexThe label 3 x
:first-of-type The first in the tagThe label 3 Square root
:last-of-type The tail is in the tagThe label 3 Square root
:only-of-type The parent element has only that tagThe label 3 Square root

Property selector

The selector instructions version The commonly used
[attr] Attribute specifiedThe element 2 Square root
[attr=val] Property equal to the specified valueThe element 2 Square root
[attr*=val] Property containing the specified valueThe element 3 Square root
[attr^=val] Property that begins with the specified valueThe element 3 Square root
[attr$=val] Property ending with the specified valueThe element 3 Square root
[attr~=val] Property that contains the specified value (complete word)The element(Not recommended) 2 x
[attr|=val] Property that begins with a specified value (complete word)The element(Not recommended) 2 x

Pseudo elements

The selector instructions version The commonly used
::before Inserted before the elementcontent 2 Square root
::after Inserted after the elementcontent 2 Square root
::first-letter Elements of theThe first letter 1 x
::first-line Elements of theThe first line 1 x
::selection MouseselectedThe element 3 x
::backdrop Full screen modeThe element 4 x
::placeholder Form elementplaceholder 4 Square root

skills

With the above pre-knowledge, follow the author to experience how to skillfully use a variety of pure CSS development skills to complete some common or special layout. To make it easier for browsers to automatically calculate certain styles, you need to set box-sizing:border-box globally.

The main layout

The main layout refers to the universal placeholder layout with uniform characteristics in most cases. Master the main layout is a front-end essential skills, to develop a look at the design drawing can probably plan the overall layout premise is must be familiar with the characteristics and structure of these main layout.

Full screen layout

The classic full-screen layout consists of three parts: top, bottom, and body. It features three parts full screen stretching, top and bottom height fixed, and body height adaptive. This layout is common and is the mainstream layout for most Web application bodies. The

,

, and

tags are usually used for semantic typography, and the

sidebar or other semantic tags can be inserted inside the

.

<div class="fullscreen-layout">
    <header></header>
    <main></main>
    <footer></footer>
</div>
Copy the code

position + left/right/top/bottom

Left :0 and right:0 Declare top:0 and bottom:0 respectively to suck the top and bottom, and declare the two heights as fixed values; Declare the top and bottom of the body as the top height and bottom height, respectively. By means of absolute positioning, the three parts are fixed in a specific position so that they do not affect each other.

.fullscreen-layout {
    position: relative;
    width: 400px;
    height: 400px;
    header.footer.main {
        position: absolute;
        left: 0;
        right: 0;
    }
    header {
        top: 0;
        height: 50px;
        background-color: #f66;
    }
    footer {
        bottom: 0;
        height: 50px;
        background-color: #66f;
    }
    main {
        top: 50px;
        bottom: 50px;
        background-color: #3c9; }}Copy the code

flex

Use Flex for a more concise implementation. Display: Flex sets child nodes horizontally by default. You need to specify flex-direction:column to change the direction of child nodes to vertical. The top and bottom height are fixed, so the body needs to declare Flex :1 to make the height adaptive.

.fullscreen-layout {
    display: flex;
    flex-direction: column;
    width: 400px;
    height: 400px;
    header {
        height: 50px;
        background-color: #f66;
    }
    footer {
        height: 50px;
        background-color: #66f;
    }
    main {
        flex: 1;
        background-color: #3c9; }}Copy the code

If


needs to be scrollable, do not declare overflow:auto to make the container adaptive scrolling. This may invalidate the adaptive scrolling or cause other unknown effects due to other formatting contexts. Insert a

inside

and declare it as follows.

div {
    overflow: hidden;
    height: 100%;
}
Copy the code
Two columns of the layout

The classic two-column layout consists of left and right columns, characterized by one column of fixed width, the other column of adaptive width, and two columns of fixed and equal height. The following examples are fixed left column width and adaptive right column width, and vice versa.

<div class="two-column-layout">
    <div class="left"></div>
    <div class="right"></div>
</div>
Copy the code

float + margin-left/right

The left column declares float:left and fixed width. Since float destreames nodes, the right column declares margin-left as the left column width to ensure that the two columns do not overlap.

.two-column-layout {
    width: 400px;
    height: 400px;
    .left {
        float: left;
        width: 100px;
        height: 100%;
        background-color: #f66;
    }
    .right {
        margin-left: 100px;
        height: 100%;
        background-color: #66f; }}Copy the code

overflow + float

The left column declares the same as above, and the right column declares overflow:hidden to form an isolated BFC region.

.two-column-layout {
    width: 400px;
    height: 400px;
    .left {
        float: left;
        width: 100px;
        height: 100%;
        background-color: #f66;
    }
    .right {
        overflow: hidden;
        height: 100%;
        background-color: #66f; }}Copy the code

flex

Use Flex for a more concise implementation. The left column declares a fixed width, and the right column declares flex:1 adaptive width.

.two-column-layout {
    display: flex;
    width: 400px;
    height: 400px;
    .left {
        width: 100px;
        background-color: #f66;
    }
    .right {
        flex: 1;
        background-color: #66f; }}Copy the code
Three column layout

The classic three-column layout consists of three columns on the left, middle and right. It is characterized by two consecutive columns of fixed width, the remaining column of adaptive width and three columns of fixed and equal height. The following examples are the fixed width of the left middle column and the adaptive width of the right column, and vice versa. The overall implementation principle is consistent with the above two column layout.

<div class="three-column-layout">
    <div class="left"></div>
    <div class="center"></div>
    <div class="right"></div>
</div>
Copy the code

To make the right column width adaptive, float + margin-left is not used. If you use margin-left, you have to calculate the left middle column width.

overflow + float

.three-column-layout {
    width: 400px;
    height: 400px;
    .left {
        float: left;
        width: 50px;
        height: 100%;
        background-color: #f66;
    }
    .center {
        float: left;
        width: 100px;
        height: 100%;
        background-color: #66f;
    }
    .right {
        overflow: hidden;
        height: 100%;
        background-color: #3c9; }}Copy the code

flex

.three-column-layout {
    display: flex;
    width: 400px;
    height: 400px;
    .left {
        width: 50px;
        background-color: #f66;
    }
    .center {
        width: 100px;
        background-color: #66f;
    }
    .right {
        flex: 1;
        background-color: #3c9; }}Copy the code
Grail layout/Wing layout

Both the classic Grail layout and the twin-wing layout are composed of three columns on the left, middle and right, with two columns of fixed width, one middle column of adaptive width and three columns of fixed and equal height. It is a variant of the two-column and three-column layouts mentioned above. The overall implementation principle is the same as the n-column layout mentioned above, but some details need to be noted.

The Holy Grail layout is similar to the twin wing layout, but there is a difference. The twin wing layout requires a child node to be inserted in the middle column. In the general implementation, it is also in the middle column, how to make the middle column content is not blocked by the left and right columns.

  • The same
    • The middle column takes the first place and declares that its width and height occupy the parent node
    • Extruded left and right columns are usedfloatandMargin negativePull it back in line with the middle column
  • different
    • Grail layout: Parent node declarationpaddingLeave space for left and right columns and fix them in the space
    • Two-wing layout: The middle column inserts child nodes and declares themmarginTo make room for left and right columns, fix the left and right columns in the space

Float + margin-left/right + padding-left/right float + margin-left/right

The position of a floating node cannot be higher than that of a non-floating node. Otherwise, the floating node will sink. So when writing the HTML structure, move the middle column node after the right column node.

<div class="grail-layout-x">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>
Copy the code
.grail-layout-x {
    padding: 0 100px;
    width: 400px;
    height: 400px;
    .left {
        float: left;
        margin-left: -100px;
        width: 100px;
        height: 100%;
        background-color: #f66;
    }
    .right {
        float: right;
        margin-right: -100px;
        width: 100px;
        height: 100%;
        background-color: #66f;
    }
    .center {
        height: 100%;
        background-color: #3c9; }}Copy the code

Float + margin-left/right float + margin-left/right

The HTML structure is roughly the same, except that a child node

is inserted in the middle column. Depending on the difference, the CSS declaration will be slightly different from the Holy Grail layout mentioned above, and you can see the difference by observing the comparison.
<div class="grail-layout-y">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center">
        <div></div>
    </div>
</div>
Copy the code
.grail-layout-y {
    width: 400px;
    height: 400px;
    .left {
        float: left;
        width: 100px;
        height: 100%;
        background-color: #f66;
    }
    .right {
        float: right;
        width: 100px;
        height: 100%;
        background-color: #66f;
    }
    .center {
        margin: 0 100px;
        height: 100%;
        background-color: #3c9; }}Copy the code

Grail layout/Wing layout Flex

Using Flex to achieve the Holy Grail layout/double wing layout can ignore the above analysis, the left and right columns width is fixed, the middle column width is adaptive.

<div class="grail-layout">
    <div class="left"></div>
    <div class="center"></div>
    <div class="right"></div>
</div>
Copy the code
.grail-layout {
    display: flex;
    width: 400px;
    height: 400px;
    .left {
        width: 100px;
        background-color: #f66;
    }
    .center {
        flex: 1;
        background-color: #3c9;
    }
    .right {
        width: 100px;
        background-color: #66f; }}Copy the code
Divide the layout

A classic evenly divided layout consists of multiple columns, characterized by equal width of each column and fixed and equal height of each column. In general, it is the simplest classical layout, and since each column is of equal width, it is easy to find a way to handle it.

<div class="average-layout">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
    <div class="four"></div>
</div>
Copy the code
.one {
    background-color: #f66;
}
.two {
    background-color: #66f;
}
.three {
    background-color: #f90;
}
.four {
    background-color: #09f;
}
Copy the code

float + width

Declare each column width as an equal percentage, or width:25% if there are 4 columns. Width :calc(100% / N) width:calc(100% / N) width:calc(100% / N)

.average-layout {
    width: 400px;
    height: 400px;
    div {
        float: left;
        width: 25%;
        height: 100%; }}Copy the code

flex

Use Flex for a more concise implementation. After the node states display:flex, all the children in the generated FFC container will have the same height. Because the container’s align-items default to stretch, all the children will occupy the entire height of the container. Each column declares flex:1 adaptive width.

.average-layout {
    display: flex;
    width: 400px;
    height: 400px;
    div {
        flex: 1; }}Copy the code
Centered layout

A centered layout consists of a parent container and several child containers. The child containers are arranged horizontally or vertically in the parent container and are horizontally or vertically centered. Center layout is a very classic problem, I believe we will often encounter.

Here is the simplest and most efficient way to center. Display: Flex and margin:auto

<div class="center-layout">
    <div></div>
</div>
Copy the code
.center-layout {
    display: flex;
    width: 400px;
    height: 400px;
    background-color: #f66;
    div {
        margin: auto;
        width: 100px;
        height: 100px;
        background-color: #66f; }}Copy the code

Adaptive layout

Adaptive layout is a placeholder layout that occupies a specific percentage of any size relative to the window. The container size of adaptive layout is calculated according to the window size, even if the size of the parent node or the ancestor node changes, the container size of adaptive layout will not affect.

You can’t build an adaptive layout without Windows scale units. In CSS3, four units of length related to viewport were added. As time goes on, most browsers now have good compatibility with these four units of length. This is the most recommended length units for future scaling schemes.

  • 1vwsaid1%Window width
  • 1vhsaid1%Window height
  • 1vminsaid1%Window width sum1%Smallest window height
  • 1vmaxsaid1%Window width sum1%The largest window in height

Window width and window height correspond to window.innerWdith and window.innerHeight respectively in JS. Without considering the compatibility of earlier browsers, you can use a single line of CSS code to kill all mobile scaling schemes.

/* based on the UI width=750px DPR=2 page */
html {
    font-size: calc(100vw / 7.5);
}
Copy the code

The above code uses calc() to dynamically calculate the font-size. Calc () is the core of adaptive layout, without which all the dynamic calculations of adaptive layout cannot be implemented happily.

Calc () is a dynamic unit of calculation. Values, lengths, angles, times, and percentages can be used as parameters. By performing a mathematical expression and returning the calculated value after the operation, you can reduce the amount of manual computation or even eliminate the need for manual computation.

Calc () is hungry, all units of measurement can be used as parameters to participate in the whole dynamic calculation.

  • The numerical:The integer,Floating point Numbers
  • The length of the:px,em,rem,vw,vhEtc.
  • The Angle:deg,turn
  • time:s,ms
  • The percentage:%

Although calc() is easy to use, but the novice will inevitably encounter some pits, remember the following characteristics, I believe you can play with calc().

  • Four operations: only usable+,-,*,/As an operational symbol
  • Operation order: follow the operation order of addition, subtraction, multiplication and division, available(a)Upgrade operation level
  • Symbolic link: Each operator symbol must be usedThe blank spaceInterval up
  • Mixed calculation: dynamic calculation with different measurement units can be mixed

The third is particularly important. If you fail to comply, the browser simply ignores this property.

< HTML > < span style = “box-sizing: border-box; color: RGB (74, 74, 74); font-size: 100/750 = x/100vw

Have you ever encountered the left or right jitter of the page route in the jump process because of the scroll bar or no scroll bar in SPA? This makes the ocD patient very uncomfortable, at this time can use calc() cleverly to solve the problem.

.elem {
    padding-right: calc(100vw - 100%);
}
Copy the code

You don’t declare padding-right as the scrollbar width directly because the default scrollbar width can be different for each browser. 100VW is the window width and 100% of the content width, so 100VW-100% is the scrollbar width. Declare padding-right to keep the scrollbar in place, so the page will not shake if the scrollbar appears.

With calc() as a guarantee, you can quickly implement some layout related to the window size. For example, implement a popover with a window width of 50%.

<div class="modal">
    <div class="modal-wrapper"></div>
</div>
Copy the code
.modal {
    display: flex;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    justify-content: center;
    align-items: center;
    background-color: rgba(0.0.0.5);
    &-wrapper {
        width: 50vw;
        height: 200px;
        background-color: #f66; }}Copy the code

Of course, using calc() does not necessarily combine with window scale units. For example, the adaptive layout has known the height of some nodes and does not want to manually calculate the final node height but wants it to fill the rest of the layout space.

<ul class="selfadaption-layout">
    <div class="box-1"></div>
    <div class="box-2"></div>
    <div class="box-3"></div>
</ul>
Copy the code
.selfadaption-layout {
    width: 200px;
    height: 567px;
    .box-1 {
        height: 123px;
        background-color: #f66;
    }
    .box-2 {
        height: 15%;
        background-color: #3c9;
    }
    .box-3 {
        height: calc(100% - 123px - 15%);
        background-color: #09f; }}Copy the code

Adsorption layout

A snap layout is a placeholder layout that can occupy a specific position with any scrolling relative to the window. The window scrolls to a specific position, and the layout is fixed at that position and does not scroll with the window thereafter. The layout of the effect commonly known as adsorption effect, is a common web page effect. Top and bottom effects, for example, fall into this category and are often used in follow-through navigation, mobile ads, and hover notifications.

In the jQuery era there were a lot of plugins for snap effects, and now the three front-end frameworks have their own third-party snap components. They all have the same implementation principle: listen for Scroll event, judge the scrollTop and the target node position range, if the condition is met, the target node position is declared as fixed to positioning the target node relative to the window, so that the user looks like a fixed position on the window.

JS to achieve the adsorption effect of the code on the Internet a lot of search, not to mention the author like to play CSS, here do not stick the relevant JS code. A very rare CSS property that is rarely used here is position: Sticky. A simple two lines of core CSS code can do the same thing as a dozen lines of core JS code, so why not?

Just a quick review of the position attribute value, and I don’t need to talk about how to use it, but I think you’re all familiar with it.

The values function version
inherit inheritance 2
static The standard flow 2
relative Relative positioning 2
absolute Absolute positioning 2
fixed Fixed position 2
sticky Viscous positioning 3

When the value is sticky, the node becomes sticky positioning. Viscous positioning is a combination of relative positioning and fixed positioning. The node is relative positioning before a certain threshold crossing and fixed positioning after crossing.

<div class="adsorption-position">
    <ul>
        <li>Top 1</li>
        <li>Top 2</li>
        <li>Normal</li>
        <li>Bottom 1</li>
        <li>Bottom 2</li>
    </ul>
</div>
Copy the code
.adsorption-position {
    overflow: auto;
    position: relative;
    width: 400px;
    height: 280px;
    outline: 1px solid #3c9;
    ul {
        padding: 200px 0;
    }
    li {
        position: sticky;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #fff;
        &:nth-child(1) {
            top: 0;
            z-index: 9;
            background-color: #f66;
        }
        &:nth-child(2) {
            top: 40px;
            z-index: 9;
            background-color: #66f;
        }
        &:nth-child(3) {
            background-color: #f90;
        }
        &:nth-child(4) {
            bottom: 0;
            z-index: 9;
            background-color: #09f;
        }
        &:nth-child(5) {
            bottom: 40px;
            z-index: 9;
            background-color: #3c9; }}}Copy the code

The two lines of core CSS code are position:sticky and top/bottom: NPX. The above 5 nodes all declare position:sticky, but because the top/bottom value is different, different adsorption effect is generated.

Careful students may find that these nodes are in relative position at some rolling moments and in fixed position at certain rolling moments.

  • 1.<li>:topfor0px, scroll toThe top containerIt is
  • The second<li>:topfor40px, scroll to40px from the top of the containerIt is
  • The third<li>: no statementtop/bottom“, has been kept relative positioning
  • The fourth<li>:bottomfor40px, scroll to40px from the bottom of the containerIt is
  • The fifth<li>:bottomfor0px, scroll toAt the bottom of the containerIt is

Of course, switching to left or right can also achieve horizontal adsorption effect.

It is worth noting that the reference of sticky positioning is not necessarily position:fixed. When any ancestor nodes are not statements of the target node position: relative | absolute | fixed | sticky, and the position, fixed line. Statement when the target node closest ancestor node position: relative | absolute | fixed | sticky, the target node is relatively the ancestor nodes to produce viscous positioning. In simple terms, the way to confirm the reference is consistent with position: Absolute.

Compatibility is only marginally good. It works with browsers that have been released for the last 2 years. Compatibility between Safari and Firefox is excellent. Have adsorption effect needs of students suggest a try, to compatible with IExplorer calculate. Look forward to better development of this property, after all, adsorption layout is really a common layout.

The horizontal layout

A horizontal layout is a placeholder layout in which the nodes in a container are arranged horizontally and the overflow is hidden. Vertical layouts are common; declare overflow:hidden; width:xpx; Height: ypX can do this, but landscape layout can’t be done in a similar way.

To facilitate horizontal layout in multiple ways, the common code is broken down below.

<div class="horizontal-layout">
    <ul>
        <li>Alibaba</li>
        <li>Tencent</li>
        <li>Baidu</li>
        <li>Jingdong</li>
        <li>Ant</li>
        <li>Netease</li>
        <li>Meituan</li>
        <li>ByteDance</li>
        <li>360</li>
        <li>Sina</li>
    </ul>
</div>
Copy the code
.horizontal-layout {
    overflow: hidden;
    width: 300px;
    height: 100px;
    ul {
        overflow-x: auto;
        cursor: pointer;
        &::-webkit-scrollbar {
            height: 10px;
        }
        &::-webkit-scrollbar-track {
            background-color: #f0f0f0;
        }
        &::-webkit-scrollbar-thumb {
            border-radius: 5px;
            background-color: #f66; }}li {
        overflow: hidden;
        height: 90px;
        background-color: #66f;
        line-height: 90px;
        text-align: center;
        font-size: 16px;
        color: #fff;
        &:not(:first-child) {
            margin-left: 10px; }}}Copy the code

Some students may use inline elements for landscape layout, but you must declare overflow-y:hidden to hide the overflow in the Y-axis of the container. Since the overflow of inline elements on the current line automatically sets the remaining nodes to the next line, you also need to declare white-space:nowrap makes all inline elements typeset on one line. If a scroll bar is generated, the height of the container needs to be fine-tuned appropriately.

.horizontal-layout.inline {
    height: 102px;
    ul {
        overflow-y: hidden;
        white-space: nowrap;
    }
    li {
        display: inline-block;
        width: 90px; }}Copy the code

The above method is too tedious for the author in the development cognition. In fact, it is drunk to arrange all nodes as text. I recommend the use of Flex layout to complete the above layout, as the most common layout, I believe I do not need to say more. Have you seen the following implementation? The experience will be even better on mobile!

.horizontal-layout.flex {
    ul {
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;
    }
    li {
        flex-shrink: 0;
        flex-basis: 90px; }}Copy the code

Highlight the layout

Highlighted layout refers to a placeholder layout in which nodes in a container are arranged in the same direction and one node is prominent in a certain direction. This layout can be tricky to describe, but it’s a horizontal list of nodes arranged from left to right, with the rightmost nodes being highlighted. This is the feature of the prominent layout, prominent nodes can be in any position of the prominent layout, up and down, left and right, left and right.

Margin -*:auto is skillfully used to realize the prominent layout. Margin :0 auto is used by all block elements with fixed width.

On the same principle, when a node declares margin-*:auto, the browser automatically calculates the remaining space and assigns the value to the node. This technique must be based on a Flex layout.

<ul class="highlight-layout">
    <li>Alibaba</li>
    <li>Tencent</li>
    <li>Baidu</li>
    <li>Jingdong</li>
    <li>Ant</li>
    <li>Netease</li>
</ul>
Copy the code
.highlight-layout {
    display: flex;
    align-items: center;
    padding: 0 10px;
    width: 600px;
    height: 60px;
    background-color: #3c9;
    li {
        padding: 0 10px;
        height: 40px;
        background-color: #3c9;
        line-height: 40px;
        font-size: 16px;
        color: #fff;
    }
    &.left li{&:not(:first-child) {
            margin-left: 10px;
        }
        &:last-child {
            margin-left: auto; }} &.right li{&:not(:last-child) {
            margin-right: 10px;
        }
        &:first-child {
            margin-right: auto; }} &.top {
        flex-direction: column;
        width: 120px;
        height: 400px;
        li{&:not(:first-child) {
                margin-top: 10px;
            }
            &:last-child {
                margin-top: auto; &}}}.bottom {
        flex-direction: column;
        width: 120px;
        height: 400px;
        li{&:not(:last-child) {
                margin-bottom: 10px;
            }
            &:first-child {
                margin-bottom: auto; }}}}Copy the code

Another trick is the clever use of :not() with :first-child and :last-child. This combination allows nodes in particular locations to directly reduce attribute overwrite problems, which is easy to read and easy to install.

  • :not(:first-child): Excludes the first node, and all other nodes use certain styles
  • :not(:last-child): Excludes tail nodes, and all other nodes use certain styles

Spacing layout

Spacing layout is a placeholder layout in which the nodes in a container are arranged from left to right and from top to bottom at specific spacing. Spacing is one of the most important layouts that I consider to be common in lists. Why does this simple layout take some time to explain? I recently looked at a lot of spacing layout related CSS code on Github, and while the overall effect looks fine, the margin/padding and structure selector are messed up, so I wanted to correct the spacing layout from zero to one.

Before entering the coding process, I want to focus on explaining the finishing touch of nth-child(). Most of you will probably recognize only the everyday uses of :nth-child(n), :nth-child(2n-1), :nth-child(2n), and :nth-child(xn), but there are other uses you may not have seen. I take this opportunity to summarize all the uses of :nth-child(). N /x/y represents a positive integer, with a minimum value of 1.

  • :nth-child(n): choose the firstnAn element
  • :nth-child(odd): chooseAn odd number of locationElement, equivalent to:nth-child(2n-1)
  • :nth-child(even): chooseThe even positionElement, equivalent to:nth-child(2n)
  • :nth-child(xn): choose the firstx*nAn element
  • :nth-child(x-n)Before:xAn element
  • :nth-child(y-n):nth-child(n+x): choose the firstx~yAn element

Analyze all the features of the spacing layout, and capture the features to help translate the features into CSS code.

  • A: Determine the spacing between containers, usemarginThe statement
  • B: To determine the spacing within the container, usepaddingStatement, subsequent convenient statementbackground-color(This step can be confused with the previous step, so be careful.)
  • C: Determines the spacing between nodes near the container boundary and the container, usingpaddingDeclare containers instead of using themmarginDeclare a node (this step describes the result of the previous step)
  • D: To confirm the left-right spacing of nodes in each line, usemargin-left/margin-right(Optional) Declare a node
  • E: To confirm the spacing between the left-most column node and the container, usemargin-left:0Declare the left-most column node or usemargin-right:0Declare the rightmost column node
  • F: Except for the first row node, usemargin-topDeclare the remaining nodes
  • G: If you want the top and bottom of the container to be empty, useborder-top/border-bottomInstead ofpadding-top/padding-bottom

All of these steps can be confusing to understand in tandem, but with the following code, you should be able to understand them in no time. Take the example of arranging 3 nodes in a row for a total of 8 nodes. The final result is 3 rows and 3 columns.

<ul class="spacing-layout">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
</ul>
Copy the code
.spacing-layout {
    display: flex;
    overflow: auto;
    flex-wrap: wrap;
    margin-top: 20px; / / A
    padding: 20px; // Corresponds to B and C
    // padding-top: 0; / / G
    // padding-bottom: 0; / / G
    // border-top: 20px solid #f66; / / G
    // border-bottom: 20px solid #f66; / / G
    width: 700px; // Leave it slightly blank to display the scroll bar
    height: 400px;
    background-color: #f66;
    li {
        width: 200px;
        height: 200px;
        background-color: #66f;
        line-height: 200px;
        text-align: center;
        font-size: 20px;
        color: #fff;
        &:not(:nth-child(3n)) {
            margin-right: 20px; // Corresponds to D and E
        }
        &:nth-child(n+4) {
            margin-top: 20px; / / F}}}Copy the code

No-load layout

A no-load layout is a placeholder layout used when no nodes are in the container. How about using JS to determine if the list collection is empty to display a placeholder? It is believed that many students who use MVVM framework will use conditional judgment to render the virtual DOM. If the length of the list is not 0, the list will be rendered, otherwise the placeholder will be rendered.

<div>
    <ul v-if="list.length">.</ul>
    <div v-esle>Empty</div>
</div>
Copy the code

However, CSS provides an empty selector: Empty, which few of you will notice.

:empty acts on a node that has no child nodes, which also includes an in-line anonymous box (separate text content). The following three conditions are considered to be non-empty. If none of the three conditions occur, the state is considered to be empty, and then :empty fires.

  • Only nodes exist:<div><p>CSS</p></div>
  • Text only exists:<div>CSS</div>
  • Both nodes and text exist:<div>Hello <p>CSS</p></div>

<ul class="empty-layout">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
</ul>
<ul class="empty-layout"></ul>
Copy the code
$empty: "https://yangzw.vip/img/empty.svg";
.empty-layout {
    overflow: auto;
    width: 200px;
    height: 150px;
    outline: 1px solid #3c9;
    &:empty {
        display: flex;
        justify-content: center;
        align-items: center;
        background: url($empty) no-repeat center/100px auto;
        &::after {
            margin-top: 90px;
            font-weight: bold;
            content: "No money, no data."; }}li {
        padding: 0 10px;
        height: 30px;
        background-color: #09f;
        line-height: 30px;
        color: #fff;
        &:nth-child(even) {
            background-color: #f90; }}}Copy the code

There is also a special no-load layout that does nothing. In this case, the final rendered DOM will have only the container. If margin/padding/border is declared but width/height is not declared, the following placeholder effect will appear. A container without any child nodes declares margin/padding/border, which is embarrassing to see.

No matter, : Empty will fix it for you! Declare display: None to resolve all invalid placeholders for containers that do not have any child nodes, or for specified nodes. One move against the enemy, strength!

// Apply to all nodes
:empty {
    display: none;
}
// on the specified node
.empty-layout:empty {
    display: none;
}
Copy the code

Multiple layout

A multicell layout is a placeholder layout in which nodes in a container are arranged in a dynamic number of cells. The photo album of wechat Circle of friends is the most common multi-grid layout, when a single photo arrangement, two photos arrangement, three photos arrangement and so on, in each case, the size of the photo may not be consistent. I made a dynamic doggy photo album in memory of my dog AB. You feel pure CSS to achieve a dynamic number of multi-lattice layout.

Instead of explaining how to do it, let’s see if you can try to restore the effect using the tips I’ve listed. The main principle is to limit the range of nodes according to the structure selector. The answer to the principle can be found in this article. Remember to realize the following source ha!

<ul class="multigrid-layout">
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
    <li class="item"><img src="https://static.yangzw.vip/codepen/ab-3.jpg"></li>
</ul>
Copy the code
@mixin square($count: 2) {
    $length: calc((100%- # {$count} * 10px) / # {$count});
    width: $length;
    height: $length;
}
.multigrid-layout {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: flex-start;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
    width: 400px;
    height: 400px;
    li {
        display: flex;
        overflow: hidden;
        justify-content: center;
        margin: 5px;
        background-color: #f0f0f0;
        @include square(3);
    }
    img {
        width: 100%;
        height: 100%;
        object-fit: cover; }}// An element
.item:only-child {
    border-radius: 10px;
    width: auto;
    max-width: 80%;
    height: auto;
    max-height: 80%;
}
// Two elements
.item:first-child:nth-last-child(2),
.item:first-child:nth-last-child(2) ~ .item:nth-child(2) {
    @include square(2);
}
.item:first-child:nth-last-child(2) {
    border-radius: 10px 0 0 10px;
}
.item:first-child:nth-last-child(2) ~ .item:nth-child(2) {
    border-radius: 0 10px 10px 0;
}
// Three elements
.item:first-child:nth-last-child(3),
.item:first-child:nth-last-child(3) ~ .item:nth-child(2),
.item:first-child:nth-last-child(3) ~ .item:nth-child(3) {
    @include square(2);
}
.item:first-child:nth-last-child(3) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(3) ~ .item:nth-child(2) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(3) ~ .item:nth-child(3) {
    border-bottom-left-radius: 10px;
}
// Four elements
.item:first-child:nth-last-child(4),
.item:first-child:nth-last-child(4) ~ .item:nth-child(2),
.item:first-child:nth-last-child(4) ~ .item:nth-child(3),
.item:first-child:nth-last-child(4) ~ .item:nth-child(4) {
    @include square(2);
}
.item:first-child:nth-last-child(4) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(4) ~ .item:nth-child(2) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(4) ~ .item:nth-child(3) {
    border-bottom-left-radius: 10px;
}
.item:first-child:nth-last-child(4) ~ .item:nth-child(4) {
    border-bottom-right-radius: 10px;
}
// Five elements
.item:first-child:nth-last-child(5) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(5) ~ .item:nth-child(3) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(5) ~ .item:nth-child(4) {
    border-bottom-left-radius: 10px;
}
// Six elements
.item:first-child:nth-last-child(6) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(6) ~ .item:nth-child(3) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(6) ~ .item:nth-child(4) {
    border-bottom-left-radius: 10px;
}
.item:first-child:nth-last-child(6) ~ .item:nth-child(6) {
    border-bottom-right-radius: 10px;
}
// Seven elements
.item:first-child:nth-last-child(7) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(7) ~ .item:nth-child(3) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(7) ~ .item:nth-child(7) {
    border-bottom-left-radius: 10px;
}
// Eight elements
.item:first-child:nth-last-child(8) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(8) ~ .item:nth-child(3) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(8) ~ .item:nth-child(7) {
    border-bottom-left-radius: 10px;
}
// Nine elements
.item:first-child:nth-last-child(9) {
    border-top-left-radius: 10px;
}
.item:first-child:nth-last-child(9) ~ .item:nth-child(3) {
    border-top-right-radius: 10px;
}
.item:first-child:nth-last-child(9) ~ .item:nth-child(7) {
    border-bottom-left-radius: 10px;
}
.item:first-child:nth-last-child(9) ~ .item:nth-child(9) {
    border-bottom-right-radius: 10px;
}
Copy the code

conclusion

Many students may think CSS is very simple, but the real play can also be compared with JS. The author is engaged in the front-end field for many years, has been committed to the research and application of CSS technology, of course, really not to play, but in the process of playing to practice the knowledge fully applied to the work.

JS is important but CSS is equally important, I hope that the students like CSS pay more attention to the author, I believe that you will have more CSS harvest. When you are not willing to learn CSS, please browse the following sites, I believe you will have a different experience.

  • Personal website: Temporary supportPCBrowse, reject supportIExplorer
  • Special album: Temporary supportPCBrowse, reject supportIExplorerTo view the source code, please stampHere,

More of my CSS development experience has been written into the mining volume “Playing with the Art of CSS”, which is a small volume and the only one on CSS in the mining community. I believe that you who care about CSS will love it. I have applied for 100 copies of the booklet to sister 60 % discount code OGecoefC, like CSS students can understand the next oh.

The author has expected to read more than ten thousand nuggets

  • 15,000 words to summarize all the features of ES6:16.7 w.Reading,4500 +Thumb up quantity
  • Use CSS development skills flexibly:14.1 w.Reading,4600 +Thumb up quantity
  • Senior front-end H5 pit must pay attention to article 40 of the mobile end guide | netease three years practice:5.9 w.Reading,3800 +Thumb up quantity
  • Flexible use of JS development skills:5.5 w.Reading,1700 +Thumb up quantity
  • To senior front-end on performance optimization of the nine main strategy and six indicators | netease practice for four years:2.9 w.Reading,1800 +Thumb up quantity
  • 25 Advanced Uses of Array Reduce you Need to know:2.9 w.Reading,900 +Thumb up quantity
  • Eight hardcore skills take you rapidly improve CSS technology | Denver live summary:2.1 w.Reading,700 +Thumb up quantity
  • Use CSS variables to make your CSS more exciting:1.8 w.Reading,600 +Thumb up quantity
  • A key formatting code brings pleasure | you’re still in for each project configuration Stylelint and Eslint:1.1 w.Reading,200 +Thumb up quantity
  • Determine the browser operating environment in detail:1.1 w.Reading,200 +Thumb up quantity

conclusion

❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create more high-quality articles

Follow the public accountIQ front-end, a focus on CSS/JS development skills of the front-end public number, more front-end small dry goods waiting for you oh

  • Follow and replydataFree access to study materials
  • Follow and replyInto the group ofPull you into the tech group
  • Welcome to attentionIQ front-endAnd moreCSS/JS development skillsOnly in the public account push