HTML - Center Div

Page content

3 Ways to Center a < div >

Credits to https://twitter.com/BilliCodes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Centering a Div - Three Methods</title>
    <style>
        .container {
            height: 100vh; /* Full height */
            position: relative; /* Required for absolute positioning */
            background-color: #f0f0f0;
        }

        /* (1) Flexbox Method */
        .flexbox {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh; /* Full viewport height */
        }

        /* (2) Grid Method */
        .grid {
            display: grid;
            place-items: center; /* Center using grid */
            height: 100vh; /* Full viewport height */
        }

        /* (3) Absolute Positioning Method */
        .absolute {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%); /* Offset to center */
        }      
    </style>
</head>

<body>
    <div class="container">
        <!-- Flexbox Method -->
        <div class="centered flexbox">Centered with Flexbox</div>

        <!-- Grid Method -->
        <div class="centered grid">Centered with CSS Grid</div>
        
        <!-- Absolute Positioning Method -->
        <div class="centered absolute">Centered with Absolute Positioning</div>
    </div>
</body>

</html>

Any Comments ?

sha256: 85678db9aeded3bf6ba6bce5bf56014023c834cdd99b62f0d8427f3c12a65360