Best Ways CSS | How to Center Content, DIVs and Images in Center of Screen using CSS

In this post we will discuss the most basic yet one the most confusing Question on the Earth, we hardly find any final solution to center Images, DIV’s or elements in the center of the screen and end up with the top & left set to 50% with negative margins. well, I do so 😛

Today will discuss some of the latest and best ways to center the elements including DIVs texts and images in the center both in verticle and horizontal of parent elements.

Method 1) Setting Margin property to Auto

.child-element{
    margin:0 auto;
}

Pros:

  • Quick to apply and easy to remember.
  • Horizontally center the position of elements (But not vertical)

Cons:

  • An element should be positioned to block
  • Width should be given to element.
  • Will not work on an element with the position set to absolute or fixed.

Method 2) Setting text-align and display type to inline-block

.parent-element {
    text-align: center;
}
.child-element {
    display: inline-block;
}

By setting a parent’s text-align  to center and setting the child element’s display type to inline-block  make the child behave like inline element.

Pros:

  • No need to specify child’s width

Cons:

  • Will only center the element horizontally not vertically.

Method 3) Display type to flex

.child-element{
     display: flex;
     justify-content: center;
     align-items: center;
}

Center element horizontally as well as vertically by setting display type to flex, justify-content & align-item to center 

Pros:

  • No need to provide Width or Height.
  • The easiest and best method.

Cons:

  • Not supported in older browsers like previous from IE10

Method 4) CSS Transformation

.child-element {
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
    position: absolute;
}

In this method, we give top & left to 50% then transform it with translate’s X Y values set to -50%. But we need to set position to absolute.

Pros:

  • No need to provide Width or Height.
  • Center element Horizontally and Vertically.

Cons:

  • An element should be set to position absolute.

So I hope you will find the best option out of given above for your need. Let me know if you have some other methods.

Leave a Comment

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