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.
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: flex
โjustify-content: center
โ align-items: center
respectively.
.container{ display: flex; justify-content: center; align-items: center; min-height: 100vh; }
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; }
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; }
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
Top comments (0)