Hackernoon logoHow to put a div in the center using Flexbox by@nimaowji

How to put a div in the center using Flexbox

Author profile picture

@nimaowjiNima Owji

a Full-Stack web developer using asp.net. C#, js, win forms

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.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.