Detailed transform:translate(-50%,-50%)

            This is actually a displacement attribute. translateX moves in the x-axis direction, whereas translateY moves in the y-axis direction, and the two parameters in the translate brackets are x first and then y.

The application scenario of this sentence is to realize block centering, and the specific implementation is as follows:

<style>
        .outer {
            width: 300px;
            height: 300px;
            position: relative;
            background-color: rgb(75, 233, 27);
        }

        span {
            position: absolute;
            background-color: red;
            width: 100px;
            height: 100px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
</style>

<body>
    <div class="outer">
        <span></span>
    </div>
</body>

 Explain what the code does:

               1. First, the width and height of the outer box .outer are set. Because it is the parent, relative positioning is set. The default position is in the upper left corner, and the background color is set to green.

               2. Homogeneity is the sub-element span, position it absolutely, give it a width and height, and position it at the lower right corner of the center of the screen (imagine a cross in the middle of the screen, this span is close to the fourth quadrant), and then Using the transform property, translate it to the left by 50% of the length of the span itself, and translate it up by 50% of the length of the span itself, so that the middle box is centered. This step can be adjusted by yourself with the debugging tool of the browser, and it is easy to understand the dynamic effect

Note: After absolute positioning, the inline element span becomes a block-level element, and the width and height can be set 

The renderings are as follows:

Among them, the middle red is the span

12/20/21 Added:

To achieve such block centering, after learning flex, don't do this, it's troublesome. Direct parent box ---->

display:flex;

align-item:center;

justify-content:center;

You can achieve block centering. If you don't understand why the block is centered like this, go to the browser development tool yourself, and the flex logo will be displayed on the label of the element with flex set. Click it and look in the style, and you can set the flex layout by selection. Instead of just writing in the code, and then refreshing the page is such a hassle.

Only for novices, people who understand may find it simple

Guess you like

Origin blog.csdn.net/qq_41083105/article/details/115233510
50