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


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).


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

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <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%);

    <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>




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!

Recommended Today

DK7 switch’s support for string

Before JDK7, switch can only support byte, short, char, int or their corresponding encapsulation classes and enum types. After JDK7, switch supports string type. In the switch statement, the value of the expression cannot be null, otherwise NullPointerException will be thrown at runtime. Null cannot be used in the case clause, otherwise compilation errors will […]