loading...

CSS - Center both vertically and horizontally

drozerah profile image Drozerah ・1 min read

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>

Flexbox says :
style.css
image

CSS Grid says :
style.css
image

Voilà!

See you next time!

Drozerah

Posted on by:

drozerah profile

Drozerah

@drozerah

Software Developer currently interested in JavaScript Back-End

Discussion

markdown guide
 

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.

 

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

 

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;

 }

}