Align Div or List to Horizontal, Vertical Center to Parent

Bootstarp 4 has introduced classes to align div or list to horizontal, vertical center to it’s parent. Do you have a list inside a div and you wish to vertically align center to list items inside the parent div? And want to maintain vertical centered position as well as horizontal centering in Bootstrap when viewport size changes? I described here how Bootstrap and Non BS users can accomplish this alignment.

For more explanation, check the top navigation bar at our blog & try resizing screen. The social sharing icons on left always stay to center, both horizontally and vertically. Which classes did I use? Or what to do if you’re not  using Bootstrap?

Align Div or List to Horizontal, Vertical Center to Parent

Align Div or List to Horizontal, Vertical Center to Parent

The text-center class in Bootstrap aligns content horizontally but not vertically. Also it’s not made to do the same if content are in a div or list where the div or list is needed to position center. So check a typical structure of Bootstrap markup.

Here you notice, I have two columns and last columns might have more content than the first one. I need to make unordered list in first column to be horizontal, vertical center to it’s parent having id align-content. Now notice line #5 in code above. It’s already done there as needed.

In line #5, the class d-flex is rendering the div as flexbox rather than a block. justify-content-center class is making flexbox items in parent to place themselves as center in horizontal and align-items-center is used to center it vertically. All the classes given in Bootstrap 4 flexbox utility and you can read about them by clicking link.

Also a little properties are needed to assign the parent div to maintain responsive behavior.

The parent div here referred, would have minimum 40px height in all case (useful when columns are stacked vertically). And 100% height property is needed to let it work.

If you’re not using Bootstrap, the horizontal, vertical center alignment classes used are given here:

Al through this post is Bootstrap 4 specific and flexbox classes are given for non BS users too. Still you can also accomplish the same horizontal, vertical center to parent div using classes provided in the article given here.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.