get div to be center of screen

how can i get a div to be centered on the screen and should stay fixed there?
6 Replies
Tenkes
Tenkes8mo ago
Use position: fixed in css
Tok124 (CSS Nerd)
.classname {
position:fixed;
top:50%;
left:50%;
translate:-50% -50%;
}
.classname {
position:fixed;
top:50%;
left:50%;
translate:-50% -50%;
}
NefariousApe
NefariousApeOP8mo ago
ok i think its center hard to tell, but why does 50% work i thought doing top and left 50% would cause its top left corner to be center, ie all of it would be in the 4quadrant
Tok124 (CSS Nerd)
If you only use top:50%; and left:50%; then it will put the top left corner of the box to be exactly in the center of the screen, so you have to use translate to move it 50% of it's own width back to the left and move it 50% of it's own height up, so then it will be perfectly centered
NefariousApe
NefariousApeOP8mo ago
oh interesting, thank you!
Chris Bolson
Chris Bolson8mo ago
Another method is to use inset and margin:
.fixed-center{
position: fixed;
inset: 0;
margin: auto;
}
.fixed-center{
position: fixed;
inset: 0;
margin: auto;
}
Want results from more Discord servers?
Add your server