Home > Software design >  I am unable to center a div both horizontally and vertically
I am unable to center a div both horizontally and vertically

Time:09-06

I used Flexbox on my div but it still only centers horizontally and not vertically. I want it in the middle of the screen. Here is my code -:

 <!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>Test</title>
    <style>
        .box{
            background-color: red;
            border: 2px solid black;
            width: 100px;
            height: 100px;
            }
        .container{
            display: flex;
            justify-content: center;
            align-items: center;
        }   
    </style>
</head>
<body>
    <div >
        <div >Box1</div>
    </div>
</body>
</html>

Here is my output -:

Output

Any help would be great.

Thank You.

CodePudding user response:

set the height and width of the container to 100vh and 100vw

CodePudding user response:

add height in your parent .container class it will take full height

.container{
  display: flex;
  justify-content: center;
  align-items: center;
  height:100vh;
}

CodePudding user response:

 .box{
    width: 50px;
    height: 50px;
    background-color: red;
    /* Center vertically and horizontally */
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -25px 0 0 -25px; /* Apply negative top and left margins to truly center the element */
 }
.container{
  display: flex;
  justify-content: center;
  align-items: center;
}   
<div >
        <div >Box1</div>
</div>

  • Related