DEV Community

Drozerah
Drozerah

Posted on

CSS - Center both vertically and horizontally

Say you have a HTML <body></body> tag and you want its child <div></div> to be centered both vertically and horizontally with modern CSS : how to achieve that ?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div>
        <h1 class="title">Hello DEV!</h1>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Flexbox says :
style.css
image

CSS Grid says :
style.css
image

VoilΓ !

See you next time!

Drozerah

Top comments (3)

Collapse
 
maxart2501 profile image
Massimo Artizzu

Nice, it's good to remind those properties from time to time. I don't use them mainly because they haven't been supported for long, and Edge still doesn't (not until we'll have Chromium Edge). But cool nonetheless.

Just a suggestion: don't use Carbon or other services that convert your code into images. It's bad for accessibility πŸ˜•

The usual triple backticks would be fine.

Collapse
 
shimphillip profile image
Phillip Shim

Cool! Didn't know there was attribute called place-items. Thanks.

Collapse
 
drozerah profile image
Drozerah

Yep !

body{

 place-items: center;

}

is the equivalent shorthand notation for :

body{

 justify-items: center;
 align-items: center;

}

And we also have place-self when it comes with child self position :

scss notation


body{

 height: 100vh;
 display: grid;

 myChild{

  place-self: center;

 }

}

for

scss notation


body{

 height: 100vh;
 display: grid;

 myChild{

  justify-self: center;
  align-self: center;

 }

}