Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 28, 2022 08:57 am GMT

Top 3 Ways to Center a DIV with CSS

In this blog will go over three approaches of centering a div.

The most difficult thing a web developer will ever have to accomplish is use CSS to center a div both horizontally and vertically.

Table of Contents

  1. Classic approach
  2. Flexbox approach
  3. Grid Layoutcenter div

1. Classic approach

Classic approach
There are hundreds of methods to do the task, but the traditional method is to use absolute positioning, then move it down and to the right by 50%by using the top and left properties, and then move it back the other way by translating it 50%. Until flexbox came along, this perplexing hack was the gold standard.

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

2. Flexbox approach

Flexbox approach
The Flexible Box Layout Module facilitates the creation of flexible responsive layout structures without the use of float or positioning.
We can use Flexbox to turn the parent div into a flexible column or row, then align and justify the children in the center.

.flex {    display: flex;    align-items: center;    justify-content: center;}

3. Grid Layout

Grid layout
Flexbox is a nice choice, but we can now accomplish it with even less lines of code by using Grid layout to detect the parent div as a grid and then instruct it to centerthe components.

.grid {    display: grid;    place-items: center;}
Thank you for reading this article; do follow me for more.

Original Link: https://dev.to/iarchitsharma/top-3-ways-to-center-a-div-with-css-2ch3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To