Note source: Silicon Valley Web front-end HTML5&CSS3 beginners zero basic entry complete version

[TOC]

Introduction to Positioning

Demand analysis

How can we do that based on what we’ve learned?

It shouldn’t be hard. It should be easy to implement

.box2 {
    width: 200px;
    height: 200px;
    background-color: yellow;
    /* Left margin, upper margin */
    margin-left: 200px;
    margin-top: -200px;
}

.box3 {
    width: 200px;
    height: 200px;
    background-color: orange;
    /* Upper margin */
    margin-top: 200px;
}
Copy the code

Once we add margins to box2 and box3, we’ll have the desired effect

You can also use a float to solve the above problem, but it’s a little more complicated

Either way, the problem is obvious. In our actual development, there may be a lot of elements on the page, so this change is bound to affect the whole

So just relying on the layout knowledge we learned before is not enough to easily cope with this scenario

Then there is the need for a convenient way to deal with this scenario, and it is positioning

Position

Positioning is a more advanced means of layout

Positioning allows you to place elements anywhere on the page

Use the position property to set the location

An optional value meaning
static Without positioning enabled, elements are static, default
relative Enable absolute positioning of elements
absolute Enable absolute positioning of elements
fixed Turns on the fixed positioning of elements
sticky Turn on the sticky orientation of the element

1. Relative positioning

When the position attribute of an element is set to relative, the relative positioning of the element is enabled

Offset

When relative positioning of an element is enabled, the position of the element can be set by the offset

Offset attribute meaning
top The distance above the positioning element and the positioning position
bottom The distance below the positioning element and position
left Distance to the left of the positioning element and position
right The distance to the right of the positioning element and position

The vertical position of the positioning element is controlled by the top and bottom attributes, and usually only one or the other is used

  • topThe larger the value, the lower the positioning element
  • bottomThe larger the value, the positioned element moves up

Positioning the horizontal position of an element is controlled by two attributes, left and right, and usually only one of them is used

  • leftThe larger the location element, the farther to the right
  • rightThe larger the positioning element, the farther to the left

Ok, after introducing the relative layout, does our requirement become so easy?

.box2 {
    width: 200px;
    height: 200px;
    background-color: yellow;
    /* Enable relative positioning */
    position: relative;
    top: -200px;
    left: 200px;
}
Copy the code

We position Box2 relative to each other and get the page we want

As you can see, when relative positioning is used, it only moves its own layout position without having any effect on existing elements

This example is not obvious, but when the page layout is complex, especially when there are many elements on the page, the advantages can be greatly demonstrated

The characteristics of relative positioning

  1. When relative positioning is enabled on an element, if the offset element is not set, the element does not change at all (note that not only the position).

  2. Relative positioning is positioned with reference to an element’s position in the document flow (which can be interpreted as relative to its original position)

  3. Relative positioning raises the level of an element (in the form of overlaying other elements)

  4. Relative positioning does not change the nature of the element: block or block, inline or inline

Q1: What is the hierarchy of the three divs if they are positioned relative to each other? Or who will be covered by whom?

A: Seeing is believing. Just talking is not practicing. We will test and verify it directly

You can see that the overlay relationship is: box3 >> box2 >> box1

Let’s reposition box3 and Box2 a little bit

The overlay relationship becomes: box2 >> box3 >> box1

It is possible to guess: in the page document flow, the lower the element is, the higher the hierarchy is after relative positioning is enabled (this is just my personal guess and will be verified in the follow-up study) (it has been verified in the follow-up study: when the hierarchy is not set or the z-index of the hierarchy is set to the same value, the lower element is preferentially displayed)

Q2: The third feature of relative positioningRelative positioning raises the level of an elementIs it like floating out of the document flow?

A: We can compare the difference between floating and relative positioning

  • Different reference frame: floating reference frame is parent element; Relative positioning is relative to oneself
  • Different moving directions: floating can only move left and right; Relative positioning is up, down, left and right
  • Different effects: floating will affect the layout of the page (including the influence of the position of the elements below and height collapse); Relative positioning does not affect page layout
  • Different properties: float changes the nature of the element (no longer a single row, its width and height are stretched by the content); Relative positioning does not change the nature of the element
  • Text surround: Float does not overwrite text Relative positioning can overwrite text (this can be verified by yourself and will not be described again)

Of course, there are similarities between floating and relative positioning

  • Float and relative positioning are both moving positions.
  • Floats and relative positions are not removed from the parent element

As you can see, the difference between floating and relative positioning is more

One final answer: floats leave the document flow and no longer occupy page position; Relative positioning still occupies page position (so how can you call it out of document flow?).

Q3: The fourth feature of relative positioningRelative positioning does not change the nature of the element: block or block, inline or inlineBut in the above example, the element does not seem to own a row after relative positioning is enabled.

A: Relative positioning does not change the nature of elements as compared to floating elements is actually A relatively difficult problem to understand. But in fact, it is not difficult, you can think of the relative positioning as the element’s out-of-body. After its position is changed, the layout doesn’t matter because its body (structure) still occupies the same position. It’s just that the soul (content) has moved.

Q4: The fourth characteristic of relative positioningBlock is block, line is lineDoes that mean that inline elements can also use relative positioning?

A: To see is to believe, but to hear is to believe

It’s good to think, but don’t forget to do it yourself.

2. Absolute positioning

When the element’s position property is set to absolute, the absolute positioning of the element is enabled

The characteristics of absolute positioning

  1. If absolute positioning is enabled and the offset is not set, the position of the element does not change
  2. When absolute positioning is enabled, the element willDetach from the document flow
  3. Absolute position meetingChange the nature of an element: The line becomes a block, the width and height of which are spread by the content (as opposed to relative positioning)
  4. Absolute position meetingRaises the element one level
  5. The absolute positioning element isPositioned with respect to its containing block(Different from relative positioning)

Containing blocks

Under normal conditions:

  • The containing block is the ancestor block element closest to the current element that has positioning enabled
  • If positioning is not enabled for all ancestor elementsHTML (root element, initial contain block)That’s its containing block
<body>
    <! Box2 contains box1 if positioning is enabled, otherwise it contains body -->
    <div class="box1">
        <div class="box2"></div>
    </div>

    <! -- If box3 is enabled, then the em contains box3, otherwise, body -->
    <div class="box3">
        <span>
            <em>hello</em>
        </span>
    </div>
</body>
Copy the code

The sample

<div class="box2">2
    <div class="box3">3
        <div class="box4">4</div>
    </div>
</div>
Copy the code

  • Instead of opening box2 and box3, box4’s contain block ishtml
  • After only positioning box3 is enabled, box4’s contain block is Box3
  • Box4’s contain block is Box2 after only positioning box2 is enabled
  • After positioning both box2 and box3, box4’s containing block is Box3

Note: The condition is to enable position, that is, as long as position is not static (the default), it meets the necessary condition to be a containing block

In the example above, we set the relative positioning of the ancestor elements. In fact, it is possible to change to several other positioning methods, we can see the following example

Here is not an example, we can verify the other several positioning methods

Horizontal layout

We said before that the horizontal layout equation:

Margin-left + border-left + padding-left + width + padding-right + border-right + margin-right = width of parent element

When using absolute positioning, you need to add the left and right values (the rule is the same as before, but two more values are added)

Left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-right + right = width of parent element

When excessive restraint occurs

  • If you don’t have any of the nine valuesauto, automatically adjustsrightValues so that the equation satisfies (the first seven values aremargin-right)
  • If there are nine valuesauto, automatically adjustsautoTo satisfy the equation

The auto value can be set to margin-left/margin-right /width /left /right

Because the default values for left and right are auto, if left and right are not set, they will be adjusted automatically if the equation is not satisfied

Horizontal center

<style>
    .box1 {
        width: 500px;
        height: 500px;
        background-color: #bfa;
        position: relative;
    }

    .box2 {
        width: 100px;
        height: 100px;
        background-color: orange;
        /* Set the left and right margins to auto */
        margin-left: auto;
        margin-right: auto;
        /* Absolute position */
        position: absolute;
        left: 0;
        right: 0;
    }
</style>

<div class="box1">
    <div class="box2"></div>
</div>
Copy the code

Vertical layout

The vertical layout equation must also be satisfied

Top + margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom + top = height of its parent element

Vertical center

.box2 {
    width: 100px;
    height: 100px;
    background-color: orange;
    /* Set the left and right margins to auto */
    margin-top: auto;
    margin-bottom: auto;
    /* Absolute position */
    position: absolute;
    top: 0;
    bottom: 0;
}
Copy the code

Horizontal and vertical center

Currently, we can center elements horizontally and vertically based on absolute positioning, so this method is just one of them

.box2 {
    width: 100px;
    height: 100px;
    background-color: orange;
    /* Set the left and right margins to auto */
    margin: auto;
    /* Absolute position */
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
Copy the code

summary

  • Horizontal layout equation:Left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-right + right = width of parent element
  • Vertical layout equation:Top + margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom + top = height of its parent element
  • The over-constraint rules of the above equation are basically consistent with those introduced in 06-Box Model
  • Just in the absence ofautoIs automatically adjustedtop/bottom/left/right

3. Secure the positioning

Setting the position attribute of the element to fixed enables the element to be fixed

Fixed positioning features

Fixed positioning is also an absolute positioning, so most of the characteristics of fixed positioning are the same as absolute positioning

The only difference is that the fixed location is always positioned with reference to the browser’s viewport (view window), and does not scroll with the web page’s scroll bar

The sample

Let’s give the body a higher height and let the browser scroll to see what it looks like

You’ll find that Box4 doesn’t have any unknown changes due to scrolling, which confirms the above knowledge, and you should also understand the viewport concept

Let’s compare absolute positioning

I believe that here, we should further understand the difference between fixed positioning and absolute positioning

Because fixed positioning and absolute positioning in addition to the above differences, other characteristics with absolute positioning is the same, so here will not repeat

4. Viscous positioning

Setting the position attribute of an element to sticky enables the fixation of the element

This time, let’s switch gears and look directly at the effects of viscous positioning

As you can see, the right sidebar is fixed for certain situations, and when you scroll up to a certain point it starts to change

With that in mind, let’s open the official handbook of Zeal and find the description of Sticky in Position

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.

This value always creates a new stacking context. Note that a sticky element “sticks” to its nearest ancestor that has a “scrolling mechanism” (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn’t the nearest actually scrolling ancestor. This effectively inhibits any “sticky” behavior (see the GitHub issue on W3C CSSWG).

Don’t panic, here is a rough translation (I have omitted a little here and condensed and summarized)

  • The element is positioned according to the document flow, that is, offset relative to the containing block
  • The offset does not affect the position of any other elements
  • A sticky element always “sticks” to its nearest ancestor with a “rolling mechanism” (whenoverflowforhidden,scroll,auto,overlay, even if the ancestor is not the most recent actual rolling ancestor

This is the last one that’s a little hard to understand, so don’t worry, let’s move on

The sample

We changed the navigation bar at the top of W3CSchool

/* Set a height */
body {
    height: 3000px;
}

.menu {
    width: 1211px;
    height: 48px;
    background-color: #E8E7E3;
    margin: 100px auto;
    /* Enable sticky positioning */
    position: sticky;
    top: 10px;
}
Copy the code

Because the teacher did not introduce the sticky attribute too much in the video, but only required us to understand it. Because in the actual development, it is also realized by combining JS, so I will not take you to watch it in depth here

Characteristics of viscous positioning

  • The characteristics of viscous positioning and relative positioning are basically the same(The video said that it was consistent with relative positioning, but I compared it, many characteristics are different, the feeling is trueIt’s more like fixed positioning, here in doubt)
  • The difference is that viscous positioning can hold an element in place when it arrives

Note that the sticky attribute is not compatible with IE (PS: However Microsoft has officially announced that they will stop maintaining IE in 2022 and IE will be a thing of the past. Although we often criticize Internet Explorer, as the dominant browser in those days, after being abandoned for many years, I don’t know whether we will still miss it, after all, it represents our youth passing away.)

5. Comparison of several positioning

We learned above that the Position property has five optional values

Static is the default, meaning that positioning is not enabled, so we only need to compare the four positioning methods

Positioning way The element does not change if the offset is not set Whether to leave the document flow Whether to change the nature of the element Whether to raise the element level The frame of reference
relative(Relative positioning) Square root x x Square root Refers to the position of the element in the document flow
absolute(Absolute positioning) x Square root Square root Square root Refer to its containing block
fixed(Fixed positioning) x Square root Square root Square root Refer to the viewport of the browser
sticky(Viscous positioning) x Square root Square root Square root Refer to the viewport of the browser

6. Supplement: Element hierarchy

For positioned elements, you can specify the level of the element through the Z-index attribute

  • z-indexAn integer is required as a parameter. The larger the value, the higher the level of the element, and the higher the level of the element, the higher the priority display
  • If the elements have the same hierarchy, the elements lower down are shown first
  • Ancestral elements, however high in hierarchy, do not overwhelm descendant elements

The sample

<style>
    div {
        font-size: 40px;
    }

    .box1 {
        width: 200px;
        height: 200px;
        background-color: #bfa;
        position: absolute;
        top: 0;
        left: 0;
    }

    .box2 {
        width: 200px;
        height: 200px;
        background-color: orange;
        position: absolute;
        top: 50px;
        left: 50px;
    }

    .box3 {
        width: 200px;
        height: 200px;
        background-color: salmon;
        position: absolute;
        top: 100px;
        left: 100px;
    }

    .box4 {
        width: 100px;
        height: 100px;
        background-color: skyblue;
        position: absolute;
        bottom: 0;
        left: 0;
    }
</style>

<div class="box1">1</div>
<div class="box2">2</div>
<div class="box3">3
    <div class="box4">4</div>
</div>
Copy the code

Doubtful question

Q: Does a float have a hierarchy? If so, what is the hierarchy between floats and positioning?

A: Null/None/undefined

  • tofloatSet up thez-indexIt doesn’t matter how big it is. It’s still covered
  • By default, there is no settingz-indexOr setz-indexWhen the magnitude is greater than or equal to 0,Float levelThe hierarchy is not as high as positioning
  • Set up thez-indexThe < 0,Float levelHigh level that can be located

Floating hierarchy (I don’t know if there is such a concept, itself is questionable, now it seems that there is no such concept)

7. To summarize

In general,

  • The overall structure of the page mostly adopts floating, block layout
  • Some module structure of the page is generally fine-tuned by positioning

8. Practice: Jingdong rotation map

CSS code

/* Overall center */
.box {
    width: 590px;
    height: 470px;
    /* Horizontal and vertical sides are centered */
    margin: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

/* ====== Start====== */

.img_list li {
    /* Each carousel is absolutely positioned so that it overlaps */
    position: absolute;
}

.img_list li:nth-child(1) {
    /* Static switch hierarchy */
    z-index: 1;
}

/* Global image size */
.img_list img {
    /* I set the width and height here because the images are not all the same size */
    /* But in general, these images will be cropped to the same size, so you don't need to set */
    width: 590px;
    height: 470px;
}

/* ====== End====== */

/* ====== Start====== */

.circle_list {
    height: 20px;
    /* Enable absolute positioning */
    position: absolute;
    bottom: 20px;
    left: 30px;
    z-index: 2;
    /* Reference jingdong original webpage, the overall font setting style, this setting method is not quite understood */
    /* You can leave it alone, but the spacing between each round is different */
    font-size: 0;
    text-align: center;
}

/* Rotation details */
.circle_list .circle {
    /* Set display: inline-block; Same thing */
    float: left;
    height: 8px;
    width: 8px;
    background-color: rgba(255.255.255.4);
    margin-right: 4px;
    /* Draw a circle, this is according to the course drawing method, according to the page source code is a little bit wrong */
    background-clip: content-box;
    border: 3px transparent solid;
    border-radius: 50%;
}

/* Rotation hover effect */
.circle_list .circle:hover..circle_list .circle:nth-child(1) {
    background-color: #fff;
    border: 3px rgba(0.0.0.1) solid;
}

====== End====== */
Copy the code

The HTML code

<div class="box">
    <ul class="img_list">
        <li><a href="#"><img src="assets/lbt/1.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/2.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/3.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/4.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/5.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/6.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/7.jpg" alt=""></a></li>
        <li><a href="#"><img src="assets/lbt/8.jpg" alt=""></a></li>
    </ul>
    <! -- THE structure here is not exactly according to the structure in the course, but the effect is the same -->
    <ul class="circle_list">
        <li class="circle"></li>
        <li class="circle"></li>
        <li class="circle"></li>
        <li class="circle"></li>
        <li class="circle"></li>
        <li class="circle"></li>
        <li class="circle"></li>
        <li class="circle"></li>
    </ul>
</div>
Copy the code

Don’t forget to introduce the reset style

The effect

Wait until the back to learn JS, you can achieve automatic round seeding, then complement perfect

The main use of

  • Horizontal and vertical directions are centered (horizontal and vertical direction equation)
  • absoluteTurn on absolute positioning, so that it overlaps, to achieve hiding effect
  • z-indexSet the hierarchy, the realization of picture rotation
  • border-radiusA circle,transparentThe border is transparent,background-clip:content-boxHidden border