Home > database >  Simple Verticle and Horizontal CSS
Simple Verticle and Horizontal CSS

Time:09-04

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 >
  
            
                
<img src="https://place-hold.it/25x25" />

            </div> </body>

Horizontal center : Success

Vertical center : failed

with above two CSS code.

CodePudding user response:

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 >
    <img src="https://place-hold.it/25x25" />
  </div>
</body>

CodePudding user response:

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 >
    <img src="https://place-hold.it/25x25" />
  </div>
</body>

CodePudding user response:

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 >
    <img src="https://place-hold.it/25x25" />
  </div>
</body>

CodePudding user response:

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 >
    <img src="https://place-hold.it/25x25" />
  </div>
</body>

  • Related