Wed Sep 28 2022

Keep Element in the Middle

CSS3113 views

File Name: keep-element-in-middle.html

<!DOCTYPE html>
<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>How to Keep Object in Center</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background-color: #292929;
        }

        section {
            width: 100%;
            height: 100vh;
            /* display: flex;
            justify-content: center;               Step 1
            align-items: center; */
            position: relative;
        }

        .box {
            width: 100px;
            height: 100px;
            background-color: #fff;
            position: absolute;
            /* top: 50%;
            left: 50%;                            Step 2
            transform: translate(-50%, -50%); */

            top: calc(50% - (100px / 2));    /*   Step 3          */
            left: calc(50% - (100px / 2));
        }
    </style>
</head>
<body>
    <section>
        <div class="box"></div>
    </section>
</body>
</html>

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.