paint-brush
How to put a div in the center using Flexboxby@nimaowji
130 reads

How to put a div in the center using Flexbox

by Nima OwjiJanuary 18th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How to put a div in the center using Flexbox? My name is Nima Owji and I want to show you how to put a div in the center using Flexbox.

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How to put a div in the center using Flexbox
Nima Owji HackerNoon profile picture

Hello, My name is Nima Owji. Today, I want to show you "How to put a div in the center of the page using Flexbox". Let's start!

Creating The Files

First of all, we should create our files.

  1. index.html
  2. styles.css

We will write our styles in "styles.css".

Writing HTML Codes

OK, now, we should write our HTML codes:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Centered Div</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div class="container">
      
    </div>
  </body>
</html>

As you can see here, I linked "styles.css" as a stylesheet and I also created a

div
in the body. That
div
has a "container" class, we will use this class to add some styles to it!

After this, we don't see anything because our

div
is empty!

Writing CSS Styles

In "styles.css" we should make

body
and
html
tags fullscreen. We will do it by changing the
height
to "100vh".

html, body
{
  height: 100vh;
}

They are fullscreen now! After that, we should add a background-color to the

container div
to make it visible. We should also add
height
and
width
to that
div
.

.container
{
  background-color: #efefef;
  width: 70vw;
  height: 78vh;
  border-radius: 5px;
}

I also added a

border-radius
to make it more beautiful!

Now, you should see something like this:

We can see this

div
but it's not in the center yet!

Putting the
Div
in the Center

For that, first, we should select

body
and
html
tags and set their
display
to
flex
.

html, body
{
  height: 100vh;
  display: flex;
}

After that, we should use

justify-content
to put that
div
in the center horizontally!

html, body
{
  height: 100vh;
  display: flex;
  justify-content: center;
}

Now, our page looks like this:

It's horizontally in the center but we should put it in the center vertically too. What should we do? We will use

align-items
for that!

html, body
{
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

It's now finished and it's in the center of the page!

You can do it in many other ways but it's one of the easiest!

You can also add more styles like
box-shadow
to the container div to make it more beautiful!

Finished!

Thanks a lot for your reading. If you liked this, please tweet it and mention me too! If you had a question, please don't hesitate to contact me on Twitter.