CSS

Best 3 Ways to Center a Div with CSS

A beginner person always faces the problem of center div on a webpage.

Rajdeep Singh
Nerd For Tech

--

I’m Face lots of trouble maybe you also. When I center div in the web page, one browser center div properly, and other browsers do not properly work. That reason CSS is very confusing for beginner people. You try some other CSS property to center div. But you fail.

In This article, we cover the top three ways to center div with CSS. We do not use any advanced CSS. We only use basic CSS property to center div.

Center a Div with CSS
Center a Div with CSS

Let’s start it.

  1. First ways
  2. Second ways
  3. Third ways

First ways

Firstly, we use the CSS position property. which is a common way to center div in CSS. Lots of time, I use position property to center div. this is a very easy and old technique to center div.

HTML code

<div class="center">

CSS code

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

Demo

First ways example

Second ways

secondly, we use flexbox to center div in a web browser. Flexbox functionally helps to center div very easily. These are new ways to center div as compare first ways.

Flexbox design a one-dimensional layout in your browser. Bootstrap also uses flexbox property to center div in a web browser.

HTML code

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

CSS code

.flex{
display: flex;
align-items:center;
justify-content: center;
}
/* center class for add style in div */.center{
background-color: black;
width:250px;
height: 250px;
}

Demo

Second ways example

Third ways

Thirdly, we use a grid layout to center div in the web browser. Grid layout new ways to center your div. the grid system is very cool and easy to use. The grid system very effectively designs a 3D website layout. I'm also recommended to use a grid system in the website rather than use any CSS framework.

HTML code

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

CSS code

.grid{
display: grid;
place-items:center;
}
/* center class for add style in inner div */.center{
background-color: black;
width:250px;
height: 250px;
}

Demo

Third ways example

--

--

Rajdeep Singh
Nerd For Tech

JavaScript | TypeScript | Reactjs | Nextjs | Rust | Biotechnology | Bioinformatic | Frontend Developer | Author | https://linktr.ee/officialrajdeepsingh