DEV Community

Cover image for 3 ways to centre a DIV with CSS 😎
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

3 ways to centre a DIV with CSS 😎

Hello Folks 👋

What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have the intention to become a successful developer.

Today, I am here with a cool topic that is one of the most searched topics on Google ("How to centre content with CSS?") related to CSS.
CSS trend on google search

Now, you don't need to bother about that; In this article, I have covered all four efficient and simple ways to centre content in CSS 😮


Flexbox


Using flexbox to centre the content vertically and horizontally is a very simple and preferred method. You can do it with just 3 lines of code: display: flexjustify-content: centeralign-items: center respectively.

.container{
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Grid


Using the grid to centre the content is very similar to the flexbox method. The only difference is, display should be set to grid instead of flex i.e. display: grid.

It is very beneficial when using the grid in layout.

.container{
  display: grid;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Transform


You can transform content to centre with the transform method.

It can be done by setting the position of the parent element relative, which allows the child element to utilize position: absolute.

After that, we can give offset to the element of left: 50% and top: 50% and transform them to transform: translate(-50%, -50%).

Btw, it's a pretty long method and a bit complicated for my beginner friends.

.container{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

So, this was it for this article. I hope you learnt something new and enjoy reading. Stay tuned for the next article.

Let's connect on Twitter - @codewithsnowbit

🌏 Let's connect

Buy me a coffee

Top comments (0)