Horizontally Center items with CSS
Posted By : Vijendra Kumar | 12-Jan-2017
Many ways to make horizontal align center items with CSS. Sometimes we got stuck to make elements horizontal align center but this is not not a big deal to do that because there's so many different ways to make it work. It's all depending on the conditions, which solution is better.
So let's get start and make a situation tree for right solution:.
1.) If it is inline-* or inline elements (like links or text) or span, a, etc ?
For make inline elements horizontal align center inside block-level parent element, you can use this below:
/*--- add this class to parent --- */
.center-children {
text-align: center;
}
This css code will work for inline-block, inline-table, inline-flex, inline, etc.
2.) If it is a block-level element like div and p etc.
For making element center assign margin-left auto and margin-right auto to a block-level element which has fixed width in px or %. That's can be write in shorthand way like this:
.center-me {
margin: 0 auto;
}
This will surely work and it is not required fixed width of block level element or the parent.
3.) If there's multiple block level element exists.
If there is multiple block level elements situation that you want to be horizontal center align in a parent row then you can use the display inline-block property. Example of making them center with child inline-block with parent text-align center:
.inline-block-center {
text-align: center;
}
.inline-block-center div {
display: inline-block;
text-align: left; /*anything you like*/
}
And also an example of flexbox:
.flex-center {
display: flex;
justify-content: center;
}
And if you have multiple container of block level and they stacked on top of each other, in this case you can use the margin left right auto technique which is still works fine which showed in 2nd point.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vijendra Kumar
Vijendra is a creative UI developer with experience and capabilities to build compelling UI designs for Web and Mobile Applications. Vijendra likes playing video games and soccer.