How To Center An Element With CSS | 2023

How To Center An Element With CSS | 2023

A brief blog about centering an element with CSS.


Here is a structured outline of how to center an element with CSS,

Structured Outline ...

  • About, the Margin

  • About, the Padding


CSS is the language we use to style a Web page.

About, the Margin

  • Margins are used to create space around elements, outside of any defined borders.
    πŸ‘‰ For more details, refer here!

  • To center an object with a margin using CSS, we can use the margin property along with auto value:

.container {
width: 40%;
margin: 3rem auto;
height: 100vh;
}

Note: Here are some key points to consider while using the margin property,
and here they are:-

  • Width:
    (a) It is important as it determines the container's width. The margin auto property will not be effective if it is not set.
    (b) The margin property is set to 0 auto. As it tells the browser to automatically calculate and evenly distribute the left and right margins of the div, thus centering it horizontally.
margin: auto;

About, the Padding

  • Padding is used to create space around an element's content, inside of any defined borders.
    πŸ‘‰ For more details, refer here!

  • Positioning is a CSS concept that allows you to control the placement of an element on a web page. It is often used to center an element horizontally or vertically within its parent container.
    To center an object with position using CSS, we can use the position and transform properties:

.container {
  width: 40%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Note: Here are some key points to consider while using the position property,
and here they are:-

  • The position property is set to absolute which allows to position it relative to its nearest positioned ancestor which is usually the body element.

  • The top and left properties are set to 50%. This allows positioning the top-left container at the center of its positioned ancestor.

  • The transform property allows the container to move up and left by half its width, respectively. I.e; -50% container moving left by 50% of its width and
    -50% container moving up by 50% of its height.

There are various techniques to achieve the same which we discussed in this blog, but there are other techniques as well to center an element with CSS.


In the upcoming blogs, I will be covering other concepts as well related to CSS.
If you love this blog, feel free to share it with your friends. πŸ‘


πŸ”— Social Links (Let's connect):
β–Ά Instagram: instagram.com/ahangar_aadil?u...
β–Ά LinkedIn: linkedin.com/in/ahangaraa...
β–Ά Telegram: t.me/ahangaraadil
β–Ά Facebook: facebook.com/ahangaraadil...

πŸ“ŒResume aka CV (ongoing ...)
β–Ά Google Drive Link: **https://drive.google.com/file/d/15QBZfoyvXzwGJoIn9cqfVkLl757IWNCX/view?usp=share_**link

Β