Div in Center of Screen

4 Easy Tricks in 4 minutes 1

HTML Code

Create a container div.

Add a div inside container class div and give a class to it (here i have use “center” class)

Below is HTML file Code.

<div class="container">
    <div class="center"></div>
</div> 

CSS Code

We can use 4 methods to align a div at the center of screen.

Add height and width to “container” class div  as well as to “center” class div.

 

I have used container background-color: rgba(214, 214, 214);

And Center div background-color: #b67d8f;

#Method 1 using position fix / position absolute and transition transform.

.container  {
    position: relative;

}

.center {

    height:100px;

    width:200px;

    position:fixed;

    top: 50%;

    left: 50%;

   transform: translate(-50, -50);

/* Browser compatibility/ Browser support*/

-webkit- transform: translate(-50, -50); /* Safari and Chrome */

-moz- transform: translate(-50, -50); /* firefox */

-ms-transform: translate(-50, -50); /*  Internet Explore */

-o-transform: translate(-50, -50); /*  Opera */

}
  

NOTE :

Use webkits for browser Compatibility.
You can also use ” position : absolute ” instead of ” position : fixed “.

#Method 2 using position fix / position absolute and transition transform.

.container {

    position: relative;

}

.center {

    height:100px;

    width:200px;

    position:fixed;

    top: 50%;

    left: 50%;

    margin-top: -50px /*Negative half of  height*/

   margin-left: -100px /*Negative half of  width*/

}


 

#Method 3 Using display flex

.container {

    height: 100vh;

    display: flex;

    justify-content: center;

    align-items: center;

}

.center {

    height:100px;

    width:200px;

} 

#Method 4 using place items center.

.container  {
    height: 100vh;

    display: grid;

    place-items: center;

}

.center {

    height:100px;

    width:200px;

} 

Watch Below Video for Detail Understanding

Leave a Reply

Your email address will not be published. Required fields are marked *