Sign in
Log inSign up
How to center anything in CSS

How to center anything in CSS

Shubam Bhasin's photo
Shubam Bhasin
·Feb 3, 2021·

2 min read

Centering div, p tags etc. is always considered as a tedious task. Most developers find it very difficult to do that. One method is very simple but it have its own drawbacks i.e., by making the div or p or whatever you have to center as absolute and then b using top, right, bottom, left properties you can do that. But it is not a good way always when you have a responsive design.

A good way ( no way is perfect ) is by using flexbox.

Let us say that you have a

<div class="center"> Hello </div>

and you have to center this !

  1. Wrap this div in another div and give it any class name you like
<div class="container>
   <div class="center">Hello</div>
</div>
  1. Now give this container class the following properties
.container
{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

and you will see that the text Hello will be in center of the screen. :)

See how easy it was.

Few points to remember

  1. justify-content align the content horizontally.
  2. align-items align the content vertically.

if flex-direction is set to column ( by default it is set as row ) then the both of the above properties interchange. Now justify-content aligns content vertically and align-items align content horizontally

Hope this little piece of information helps you. Please leave your positive/negative feedback. That will only help me improve and contribute to the community.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct