How to horizontally align extra columns to center using bootstrap 4

My requirement was to align six columns to center but with only four columns in one row due to the width constraint as shown in the picture below. So what should happen to the rest of the two columns. They wrap to the next line. But towards the left. So how do you pull these extra columns to the center or the grid!!!

bootstrap col center output
bootstrap col center

The bootstrap 4 is based on CSS Flex box and provides several classes which mimic the alignment and display properties of the flex box. In our case where have a class called justify-content-center which is applied to a row. This helps pull the direct inner child elements to the center horizontally. Now this bootstrap class is similar to the CSS Flex property justify-content, which is applied to a flex container to align it’s child elements horizontally. In our case it needs to be in center.

So here is how it works using bootstrap 4:


Using CSS flex box

With CSS its pretty easy to achieve same result. To do that, set the display of the parent container to flex and set the justify-content property to center. Notice that with CSS we require to add one more property called flex-wrap  and set it to wrap. The default value of flex-wrap property is nowrap, because of which flex container tries to adjust the child elements in the same line instead of wrapping to next line. Hence we override the default value of flex-wrap with the value wrap. We have set the with property of the container(800px) and the chlidren DIVs(200px), so that we can easily get two of the DIVs to to the next line. Here is how:

CSS code

CSS flex justify content
CSS flex justify content

HTML code

html justify content
html justify content

Here are full working examples of both ways: with bootstrap and with only CSS.





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s