4 ways to vertically center with CSS
Hey, there today I am going to show you some old and some new ways to vertically item in CSS. Vertically centering things with CSS used to be a challenge, but now there are so many ways to do it.
The 4 ways I am going to write are the old school way with a table cell, using position absolute, to new techniques, using flexbox and grid's align-items property.
1.
Using table cell
Here is HTML code and preview.
<!-- table -->
<h2 class="title">table</h2>
<div class="table">
<p>Center me!</p>
</div>
as we see our p text is in the top center of the table container. We can use display: table behavior to align items in the vertically center of the container, is it old school now a days but it's easy and effective.
.table {
display: table;
}
.table p {
display: table-cell;
vertical-align: middle;
}
output:-
As the above result all our output same like this.
2.
Using Absolute Behaviour
<!-- position absolute -->
<h2 class="title">absolute</h2>
<div class="absolute">
<p>Center me!</p>
</div>
Its the most popular method among developers.
.absolute {
position: relative;
}
.absolute p {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
}
when I use top:50% my content is out of the container because of my container size, so in my absolute parent I have to use relative to fix that, if you dont know what is position: relative, absolute you can read about more on developer.mozilla.org/en-US/docs/Web/CSS/p… . At a final using translateY and width, my content is in the center.
3.
Using Flexbox
<!-- flexbox -->
<h2 class="title">flexbox</h2>
<div class="flexbox">
<p>Center me!</p>
</div>
its just a three line of code From that you can imagine how easy this meathod is that😂
.flexbox {
display: flex;
align-items: center;
justify-content: center;
}
4. Using Grid
<h2 class="title">grid</h2> <div class="grid"> <p>Center me!</p> </div>
grid {
display: grid;
align-items: center;
justify-content: center;
place-items: center;
}
Grid Is the modern And most used method currently and it is faster than Flexbox for example for the only use of display: grid and align-items: center; I get the result what I want, you see just only two lines of code is show his magic Another way is that instead of aligning items we can use justify-contain its also work some And another is using display: grid and using place-items: center
my ratings:-
- using table: 3.5/5
- using absolute: 4/5
- using flexbox: 4..3/5
- using Grid: 4.8/5