cft

Best 😃 Ways to center a div in CSS

Some of the best ways to center a div using- Flex-box or position...


user

Anmol Verma

2 years ago | 1 min read

Well If you use Bootstrap or make a Website from scratch a good understanding of CSS is needed to debug your UI

One of the most commonly used CSS features is to center a div either horizontally, vertically, or both.

Before reading if I use CSS: use the text in CSS and Bootstrap: use in bootstrap class


And there are many ways to do that either by using flex-box or position attribute...

To center a div or any text related content in a tag, one can easily use

CSS: text-align: center;
Bootstrap: text-center




Now the second and the most used way is to use flex-box i.e.

CSS: display:flex;
justify-content: center;
Bootstrap: d-flex justify-content-between

This will center the div horizontally, if you want to center it vertically also you can add padding or use line-height property or simply add align-items: center




To center a div via position absolute use:

Set the position property of the parent element to relative.

Then set the child's position property to absolute, top to 50%, and left to 50%. This just centers the top left corner of the child element vertically and horizontally.

To truly center the child element, apply a negative top margin set to half the child element's height, and a negative left margin set to half the child element's width:

width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin: -25px 0 0 -25px;




To Center a Div Vertically and Horizontally with Transform and Translate:

Use this method to center an element vertically and horizontally if you don't know its exact dimensions and can't use Flexbox.

First, set the position property of the parent element to relative.

Next, set the child element's position property to absolute, top to 50%, and left to 50%.

Finally, use transform: translate(-50%, -50%) to truly center the child element:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);



And there are many more ways to center a div but there were the best


My GitHub Profile - AnmolVerma404

My Twitter - @AnmolVe97231707

My LinkedIn Profile - Anmol Verma

Upvote


user
Created by

Anmol Verma


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles