-1

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 class="container">
        <div class="box">Box1</div>
    </div>
</body>
</html>

Here is my output -:

Output

Any help would be great.

Thank You.

rioV8
  • 24,506
  • 3
  • 32
  • 49

3 Answers3

2

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

M NARESH
  • 142
  • 1
  • 7
0

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

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

 .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 class="container">
        <div class="box">Box1</div>
</div>
Mitali Patel
  • 395
  • 2
  • 9