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

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

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

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

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.


Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of