Translate (- 50%, – 50%) in CSS to achieve horizontal and vertical centering effect

Time:2020-11-19

Translate (- 50%, – 50%) attribute:
Up and left, move 50% of its length and width to center it.

Different from using margin to realize centering, margin must know its width and height, while translate can center without knowing its width and height. The percentage in tranlate function is relative to its width and height
(when top and left are 50%, the origin is the upper left corner of the window).

Example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style media="screen">
        .container {
            position: relative;
            width: 50%;
        }

        .container img {
            width: 100%;
            display: block;
            height: auto;
        }

        .overlay {
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            opacity: 0;
            transition: 0.5s ease;
            background: rgb(0, 0, 0);
        }

        .container:hover .overlay {
            opacity: 0.5;
        }

        .text {
            color: white;
            font-size: 20px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            -ms-transform: translate(-50%, -50%);
        }
    </style>
</head>

<body>
    <h2>Fade in effect</h2>

    <div class="container">
        <img src="./img/photo2.jpg" alt="Avatar" class="image">
        <div class="overlay">
            <div class="text">Hello World</div>
        </div>
    </div>
</body>

</html>

effect:

在这里插入图片描述

This article on CSS translation (- 50%, – 50%) to achieve horizontal and vertical center effect on this, more relevant CSS translate horizontal vertical center content, please search the previous articles of developeppaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!