0

I am trying to make DIV verticle and horizontal center. I am using code from here : How can I vertically center a div element for all browsers using CSS?

I tried both

display: grid;
place-items: center;

and

display: flex;
align-items: center;
justify-content: center;

My code :

body {
                background: #000000 50% 50%;
                overflow-x: hidden;
                overflow-y: hidden;
            }
            
            .video {            
    display: grid;
    place-items: center;
            }
       <body> <div class="video">
  
            
                
<img src="https://place-hold.it/25x25" />

            </div> </body>

Horizontal center : Success

Vertical center : failed

with above two CSS code.

Sted
  • 111
  • 6

5 Answers5

1

It isn't working because elements by default have a height to fit-content. So you need to define a height higher then the fit-content height:

body {
  background: black;
  margin: 0;
}

.video {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
<body>
  <div class="video">
    <img src="https://place-hold.it/25x25" />
  </div>
</body>
tacoshy
  • 10,642
  • 5
  • 17
  • 34
1

You can just add height as 100vh in video class.

body {
  background: #000000 50% 50%;
  overflow-x: hidden;
  overflow-y: hidden;
}

.video {
  display: grid;
  place-items: center;
  height: 100vh;
}
<body>
  <div class="video">
    <img src="https://place-hold.it/25x25" />
  </div>
</body>
A.L
  • 10,259
  • 10
  • 67
  • 98
Rizeen
  • 1,296
  • 1
  • 6
  • 17
1

You need to apply height: 100%; to the div and all its ancestors (i.e. body and html in this case) for the flexbox centering method to work, otherwise it will only have the height of its contents (i.e. the image) and not fill the viewport vertically.

html, body {
  height: 100%;
  margin: 0;
}
body {
  background: #000000 50% 50%;
  overflow-x: hidden;
  overflow-y: hidden;
}

.video {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
<body>
  <div class="video">
    <img src="https://place-hold.it/25x25" />
  </div>
</body>
Johannes
  • 64,305
  • 18
  • 73
  • 130
1

body {
  background: black;
  margin: 0;
}

.video {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
<body>
  <div class="video">
    <img src="https://place-hold.it/25x25" />
  </div>
</body>
Rizeen
  • 1,296
  • 1
  • 6
  • 17
-1

If you want to center both vertically and horizontally, you can try this code below on your CSS:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height:100vh;
}
<body>
  <div class="video">
    <img src="https://place-hold.it/25x25" />
  </div>
</body>
  • Will not work. If you would have tested it yourself you would have seen that. You miss the most important detail. – tacoshy Sep 03 '22 at 13:05