Top 3 Ways To Center In CSS

Liam Zety
2 min readJan 15, 2021
Photo by Pankaj Patel on Unsplash

For some time now i encounter alot of Frontend developers that struggle with centering divs in CSS and the majority of Backend developers (that i’ve met) simply don’t want to sink in the time to make it theirs.

That’s why i’ve decided to share the Top 3 ways that i like to center using minimal CSS.

1) Via Flexbox Parent

My personal favorite, as i use mostly flexbox to structure my UI i find this the most optimal and flexible of the bunch all you need is a parent div that wraps a child:

HTML

<div class="parent">  <div class="child">
child
</div>
</div>

CSS


.parent {
display: flex; align-items: center; justify-content: center; height: 200px; /* optional */}

2) Fixed / Absolute

If you need a div that is centered and de-attached from the main markup (Modals, Menus etc…)

There are many varied ways to center fixed or absolute divs but this one is my go-to.

All you need is pre-determined width and height properties with margin auto and all X,Y axis set to 0.

HTML

<div class="center-me">centered</div>

CSS

.center-me{  position: fixed; /* or absolute */  width:fit-content;  height:fit-content;  top:0;  bottom:0;  left:0;  right:0;  margin: auto;}

3) Via A Child

This one is the most straight-forward — wrap the child with a parent div and set the child with width and a margin auto, do note however that the child will be both horizontal and vertical centered depending on the parent height.

HTML

<div class=”parent”>  <div class=”child”>
child
</div>
</div>

CSS

.child {
width: 50px;
margin: auto;
}

And… thats it! My Top 3 ways to center divs using CSS.

--

--

Liam Zety
0 Followers

Full-Stack / Frontend Web Developer