【 Different CSS】 In-depth understanding of position (master positioning is so SAO gas)

Writing in the front

Your mastery of CSS layout determines how fast you can develop pages in Web development. As Web technology continues to evolve, the number of ways to implement various layouts is endless.

Recently, I put together a series of articles in about half a month using shred time. This series summarizes the various layouts in CSS, their implementation methods and common techniques. This article series will give you a new understanding of CSS layout.

The navigation posts of this series can be entered by me, which can quickly jump to the articles you want to know (recommended favorites)

positionDescription of properties

Position is an important CSS layout attribute that specifies how an element is positioned in the document. The top, right, bottom, and left attributes determine the final position of the element.

This property has the following five values:

  • static: The default value indicates normal layout behavior. Set this parameter at this timetop.right.bottom.leftz-index Properties are invalid.
  • relative:Sets the element to a relative positioning element, which does not depart from the document flow
  • absolute:Sets the element to an absolute positioning elementMakes the element relative to the nearest nonstaticLocation The location of the ancestral element.
  • fixed: Sets the element to a fixed positioning elementTo position the element relative to the visual window.
  • sticky: Set the element to a sticky positioning element, does not leave the document flow at the default location at first, and when a certain location is reached, it is positioned relative to the viewport.

Absolute property values

The basic features

The absolute property value has the same properties as the float property name:

  1. Wrapping: Wrapping means that the width of an element shrinks to match its content.
  2. Destructiveness: Destructiveness refers to the height collapse of the parent element

Out of document flow

When the value of the position attribute is set to Absolute, its elements are removed from the document flow.

Document flow is to divide a form into lines from top to bottom and arrange elements from left to right in each line, called document flow, also known as normal flow.

When an element is no longer occupying space in the document flow, it is in a floating state (understood as floating on top of the document flow). Elements that leave the document flow are positioned based on the normal document flow, and when an element leaves the document flow, other elements still in the document flow ignore it and fill its original space.

The example code is as follows:

<! DOCTYPEhtml>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>Out of document flow</title>
        <style>
            .item {
                width: 300px;
                height: 200px;
                background-color: #ec407a;
                /* Detach from the document stream takes up no space in the document */
                position: absolute;
            }
            img {
                width: 500px;
            }
        </style>
    </head>
    <body>
        <div class="item"></div>
        <img src=". /.. /image/img.jpg" />
    </body>
</html>
Copy the code

Not leaving the document flow is shown in the figure below:

Out of the document flow is shown in the figure below:

You can see that the

element is already floating above the image.

withmarginThe common use

The absolute attribute value can be used in conjunction with margin to achieve some nice layout results. For example, a search box effect, the sample code looks like this:

<! DOCTYPEhtml>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Drop down frame set two or three things</title>
        <style>
            body {
                margin: 0;
                background-color: #edeff0;
            }
            /* Containers */
            .container {
                margin-top: 120px;
                margin-left: 240px;
                overflow: hidden;
            }
            /* Input box style */
            .input {
                width: 240px;
                line-height: 18px;
                padding: 10px;
                margin: 0;
                border: 0 none;
            }
            .input:focus {
                outline: 0 none;
            }

            .list {
                /* The default is not displayed, when input content, through the JS control its display */
                /* display: none; * /
                position: absolute;
                width: 260px;
                /* control the display position by margin */
                margin: 39px 0 0 -1px;
                padding-left: 0;
                list-style-type: none;
                border: 1px solid #e6e8e9;
                background-color: #fff;
                box-shadow: 0px 1px 2px #d5d7d8;
                font-size: 12px;
            }
            /* List item style and hover style */
            .list > li {
                line-height: 30px;
                padding-left: 12px;
            }
            .list > li:hover {
                background-color: #f9f9f9;
            }
            .list a {
                display: block;
                color: #5e5e5e;
                text-decoration: none;
            }
            .list a:hover {
                color: # 000;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <ul class="list">
                <li>
                    <a>Play with CSS layout Grid layout</a>
                </li>
                <li>
                    <a>Play with CSS layouts with Flex layouts</a>
                </li>
                <li>
                    <a>Play CSS layout in-depth understanding of position positioning</a>
                </li>
                <li>
                    <a>Play with CSS layouts with an in-depth understanding of Z-index positioning</a>
                </li>
            </ul>
            <input class="input" placeholder="Please enter content" />
        </div>
    </body>
</html>

Copy the code

The execution result is as shown in the figure below:

At this point, you can control the display and hiding of the prompt content by means of JavaScript.

B: Left, right, top, bottom

When positioning is turned on, its offset can be controlled by these four attributes, and its parameters can pass the pixel value, the percentage (which represents the percentage of the width of the block that the element contains), and so on.

Simple use here will not be introduced, here are some tips in development

  1. Full screen adaptive effects without width and height declarations

    The sample code looks like this:

    <! DOCTYPEhtml>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
            <title>Full screen adaptive effects without width and height declarations</title>
            <style>
                .overlay {
                    position: absolute;
                    /* Pull its elements all over the page */
                    left: 0;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    background-color: # 000;
                    opacity: 0.5;
                }
            </style>
        </head>
    
        <body>
            <div class="overlay"></div>
        </body>
    </html>
    Copy the code
  2. Left, right, and width are horizontally centered. The sample code looks like this:

    <! DOCTYPEhtml>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
            <title>Left, right, and width are horizontally centered</title>
            <style>
                img {
                    position: absolute;
                    right: 0;
                    left: 0;
                    width: 800px;
                    Margin-right: auto; margin-left: auto; margin-left: auto; margin-left: auto
                    margin: auto;
                }
            </style>
        </head>
        <body>
            <img src=".. /image/img.jpg" />
        </body>
    </html>
    Copy the code

    The results are as follows:

It is important to note that the absolute attribute value cannot be used with float, and float will fail if it is used together.

withz-indexThe relationship between

Elements that are absolutely located can be displayed through the Z-index control hierarchy, but this is not necessary during development when we need our code structure to be clear. The guidelines for use are as follows:

  1. If there is only one element that determines positioning, it is not necessaryz-indexTo control hierarchical display, which automatically overrides normal elements.
  2. If you have two elements that are absolutely positioned, controlling the sequence of the DOM flow will give you the desired coverage, and you don’t need itz-indexProperties.
  3. If there are multiple absolute locations interlaced, which is very rare, through the DOM stream order, andz-index: 1You can do that
  4. If not the popbox class determines the location of the elementz-indexIf phi is greater than 2, it must bez-indexIt’s redundant, and the code can be optimized.

Relative attribute values

rightabsoluteThe limiting effect of

The relative attribute has the following restrictions on absolute

  1. When the relative position is enabled for the parent element, the left, right, top, and bottom values of the child element will never exceed the values of the parent element if the relative position is enabled for the child element.

    The sample code looks like this:

    <! DOCTYPEhtml>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
            <title>The relative attribute has the following restrictions on 'absolute'</title>
            <style>
                .container {
                    /* Enable relative positioning for parent elements */
                    position: relative;
                    height: 400px;
                    width: 600px;
                    margin: 0 auto;
                    background-color: #9c27b0;
                }
                .item {
                    /* Enable absolute positioning for child elements */
                    position: absolute;
                    background-color: #4caf50;
                    height: 200px;
                    width: 300px;
                    /* The top left right bottom of the children is confined to the parent container */
                    right: 0;
                    bottom: 0;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="item"></div>
            </div>
        </body>
    </html>
    Copy the code

    The execution result is as follows:

  2. When relative positioning is enabled on both elements and both are restricted by z-index, suppose the z-index of parent element 1 is 2 and the z-index of parent element 2 is 1. The child elements below parent element 2 will never overwrite the child elements below parent element 1, regardless of the z-index value.

  3. If relative positioning is not enabled for the parent element, its overflow: hidden; There is no restriction on the child elements of absolute positioning, and the child elements of absolute positioning are restricted only when relative positioning is enabled on the parent element.

    The example code is as follows:

    .container {
        /* Enable relative positioning for parent elements */
        position: relative;
        height: 400px;
        width: 600px;
        margin: 0 auto;
        background-color: #9c27b0;
        overflow: hidden;
    }
    .item {
        /* Enable absolute positioning for child elements */
        position: absolute;
        background-color: #4caf50;
        height: 200px;
        width: 300px;
        right: 0;
        top: 0;
    }
    Copy the code

    The HTML structure is the same as above

    When relative positioning is not enabled for the parent element, the effect is as follows:

    After it is enabled, it is shown as follows:

B: Left, right, top, bottom

When relative positioning is enabled on an element, the shift is relative to itself and non-invasive to other elements. Simply put, it is a deviation from its original position, and has no effect on other elements and.

The example code is as follows:

  <! DOCTYPEhtml>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>The use of offset properties such as left</title>
        <style>
            .container {
                /* Enable relative positioning for parent elements */
                position: relative;
                height: 400px;
                width: 600px;
                background-color: #9c27b0;
                left: 100px;
                top: 100px;
            }
        </style>
    </head>
    <body>
        <div class="container"></div>
    </body>
</html>
Copy the code

The execution result is as follows:

Realtive Minimizes impact

The minimum impact principle of relative refers to the potential impact of relative attribute values on other elements or layouts! It is embodied in two aspects:

  1. When using absolute attribute value, try not to use relative to do the restriction, but use margin to complete its positioning function.

  2. When relative positioning must be enabled by the parent element and the absolute of the child element can achieve the positioning effect, you can create a parent element separately for the child element and enable relative positioning, so that the child element can be positioned relative to the parent element. The advantage of this is that the Relative layout does not affect other elements.

    The example code is as follows:

    <! DOCTYPEhtml>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
            <title>Relative Minimum impact principle</title>
            <style>
                .container {
                    height: 400px;
                    width: 600px;
                    background-color: #9c27b0;
                    margin: 0 auto;
                }
                .item {
                    height: 100px;
                    width: 50px;
                    background-color: #ff7043;
                    line-height: 100px;
                    font-size: 30px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <! Create a separate parent element with Relative positioning enabled -->
                <div style="position: relative">
                    <! -- This does not affect the positioning of the following elements -->
                    <div class="item" style="position: absolute; right: 0">1</div>
                </div>
                <div class="item">2</div>
            </div>
        </body>
    </html>
    Copy the code

    The execution result is shown in the figure below:

Fixed property values

When the value of position is set to fixed, the element is offset relative to the browser window, i.e. the reference point for positioning is the browser window. This causes the element’s position to not change as the page rolls, as if it were fixed on the page.

This attribute can also be used with the top, bottom, left, and right attributes to indicate that the initial position of the element is calculated based on the viewport. If these four attributes are not used, the starting position of the element is the default position of the element.

The sample code looks like this:

<! DOCTYPEhtml>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>Fixed property values</title>
        <style>
            body {
                margin: 0;
                height: 2000px;
            }
            .container {
                /* Open fixed location */
                position: fixed;
                height: 400px;
                background: #2c80c5;
                /* Implement the center */
                left: 0;
                right: 0;
                width: 500px;
                margin: auto;
            }
        </style>
    </head>
    <body>
        <div class="container"></div>
    </body>
</html>
Copy the code

This element is always positioned at the top, no matter how the page is scrolled.

The execution result is as follows:

Sticky attribute values

Sticky attribute value and other attribute value is not the same, the attribute value will produce a dynamic effect, flexible use of the attribute value can complete a top effect.

This value is like a combination of relative and fixed. In some cases it is relative (the positioning is based on the default position) and in other cases it is automatically fixed (the positioning is based on the viewport).

The value of this attribute must be used together with top, bottom, left, and right, and cannot be omitted, otherwise it is equivalent to relative positioning and does not produce a dynamic fixed effect.

When the page scrolls, the parent element begins to break away from the viewport, which is partially invisible), as long as the distance from the sticky element reaches the effective threshold, the relative positioning automatically switches to fixed positioning; When the parent element is completely removed from the viewport (that is, completely invisible), the fixed position automatically switches back to the Relative position.

The example code is as follows:

<! DOCTYPEhtml>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>Sticky attribute values</title>
        <style>
            .container {
                background: #eee;
                width: 600px;
                height: 1000px;
                margin: 0 auto;
            }
            .title {
                /* For Safari */
                position: -webkit-sticky;
                position: sticky;
                height: 60px;
                background: #ff7300;
                top: 0px;
                font-size: 30px;
                text-align: center;
                color: #fff;
                line-height: 60px;
            }
            img {
                width: 100%;
                display: block;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div>
                <div class="title">The content of 1</div>
                <img src=".. /image/img.jpg" />
            </div>
            <div>
                <div class="title">Content of the 2</div>
                <img src=".. /image/img.jpg" />
            </div>
            <div>
                <div class="title">The content of 3</div>
                <img src=".. /image/img.jpg" />
            </div>
            <div>
                <div class="title">The content of 4</div>
                <img src=".. /image/img.jpg" />
                <img src=".. /image/img.jpg" />
            </div>
        </div>
    </body>
</html>
Copy the code

The execution result is as shown in the figure below:

When our page is scrolling, as long as the distance between the top of the viewport and the.title >=0, the.title position is automatically fixed, keeping the distance between the top of the viewport and the 0px. As the page continues to scroll down, the parent element is completely removed from the viewport (i.e. the entire parent element is completely invisible), and the.title is restored to the relative position.

Effective rules

Position :sticky is effective with certain restrictions, summarized as follows:

  1. Must be specifiedtop.right.bottomleftOne of four thresholds is required for viscous localization to be effective. Otherwise it behaves the same as relative positioning.
    • andtopbottomSet at the same time,topThe effective priority is high.leftrightSet at the same time,leftHas a higher priority.
  2. Set toposition:stickyThe overflow property of any parent node of the element must be visible, otherwiseposition:stickyWill not take effect. Here’s what needs explaining:
    • ifposition:stickyThe location of any parent node of the element is set tooverflow:hidden, the parent container cannot scroll, soposition:stickyElements don’t scroll and then get fixed.
    • ifposition:stickyThe location of any parent node of the element is set toposition:relative | absolute | fixed, the element is positioned relative to the parent element, but not relative to the visual window.
  3. The set threshold was reached. That’s easy to understand, that’s the setupposition:stickyThe element ofrelativeorfixedIs based on whether the element has reached a set threshold.