How to center a DIV (3 Different Methods)
Here we are facing one of the most frustrating issues for developers: How to center a DIV or any other object on the page or within its containing area? 🧐
There are several ways to achieve this; we will provide examples of centering using both traditional methods and methods compliant with new standards. Of course, in line with SIPA’s ‘Less code, more work‘ rule. 😎
Let’s get started. 🔥
1. Traditional Method (Table View)
HTML:
<div class="centered">
<div class="inner">
<div class="content">
<h1>This is the centered DIV</h1>
<p>Centered method is TABLE | TABLE-CELL views.</p>
</div>
</div>
</div>
CSS:
.centered {
display: table;
width: 100%;
height: 100vh; /* set your height */
}
.centered > .inner {
display: table-cell;
width: 100%;
height: 100%;
vertical-align: middle;
}
.centered > .inner > .content {
width: auto;
height: auto;
margin: 0 auto;
max-width: 35%; /* not required */
padding: 20px; /* not required */
background-color: #ccc; /* not required */
}
2. Modern Method (Flex View)
With this method, you will see that we write less code. This is the main philosophy of coding anyway: Less code, less data transfer, faster applications.
HTML:
<div class="centered">
<div class="content">
<h1>This is the centered DIV</h1>
<p>Centered method is FLEX view.</p>
</div>
</div>
CSS:
.centered {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh; /* not required */
}
.centered > .content {
max-width: 35%; /* not required */
padding: 20px; /* not required */
background-color: #ccc; /* not required */
}
3. SIPA Method (Fixed/Relative & Absolute View)
This method is more commonly preferred for popup windows. We can center using ABSOLUTE objects within both RELATIVE and FIXED objects.
You can review and download the Flex CSS Popup codes we wrote using this method from here:https://sipa.web.tr/flex-css-popup/
HTML:
<div class="centered">
<div class="content">
<h1>This is the centered DIV</h1>
<p>Centered method by SIPA :).</p>
</div>
</div>
CSS:
.centered {
position: relative; /* or fixed */
z-index: 1;
height: 100vh; /* not required */
}
.centered > .content {
position: absolute;
z-index: 1;
inset: 0;
margin:auto;
width: max-content;
height: max-content;
padding: 20px; /* not required */
background-color: #ccc; /* not required */
}