How to align div horizontally and vertically center using CSS

How to align div horizontally and vertically center using CSS

Hello Friends 🙏, These days Front-end developers are majorly focusing on JS frameworks like React/Vue/Angular and ignoring on basics of CSS & HTML.
But there are some of HTML/CSS tasks, which every front-end developer must know. One of the tasks from that list is to align div horizontally and vertically center on the webpage. This can be very useful in interviews for a front-end job that requires HTML/CSS as a core skill.

So today in this CSS Tutorial for beginners, we will look into the options we have to complete the task 😎. Hope it will help the you to understand the logic 👍.

Chalo suru kiya jaye!🍻 Lets start! 🕺.

Creating the Basic structure

First create HTML

<html>
   <body>
      <div class="div-to-align"></div>
   </body>
</html>

Now add some stylings to give container a proper look.

/* Container, that needs to be aligned */
.div-to-align {
  width: 400px;
  height: 300px;
  border: 1px solid #000;
}

Now we can align the div using below layout options:

Option 1: Positioned Layout

In this option we use the position property and then logically place the container at center of the screen.
Check here

.div-to-align {
  position: absolute;
  /* div position will now be relative to body */
  left: 50%;
  /* div will start half way from left of the page */
  top: 50%;
  /* div will start half way from top of the page */
  margin-left: -200px;
  /* This is half width of the modal div,
        when we negate it from left, it align div horizontally center */
  margin-top: -150px;
  /* This is half height of the modal div,
        when we negate it from top, it align div vertically center */
}
align div horizontally and vertically center,align div horizontally center,css tutorial for beginners,flexbox layout

Option 2: FlexBox Layout

Flexible Box Layout, makes it easier to develop responsive layout structures without using float or positioning.
Check here

html,
body {
  /* Stretch the height of html and body to fill the viewport */
  height: 100%;
}

body {
  display: flex;
  /* This will make body a flex-container*/
  justify-content: center;
  /* This will align div horizontally center */
  align-items: center;
  /* This will align div vertically center */
}
align div horizontally and vertically center,align div horizontally center,css tutorial for beginners,flexbox layout

Thanks 🙏.

Leave a Comment

Your email address will not be published.