Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

How to horizontally center a flexible width button using only css

Ever had to hor­i­zon­tally cen­ter a but­ton only to find that unless you give it a fixed width, it wont cen­ter align. For exam­ple, it is not uncom­mon to find the below code being used to hor­i­zon­tally align a button.

.my-btn {
  width: 200px;
  margin-left: auto;
  margin-right: auto;
}

Well, although the above will work in some cases, you’re bet­ter off(at least in terms of inter­na­tion­al­iza­tion) when you allow your but­tons to be of a flex­i­ble width. But then, how do you let it be hor­i­zon­tally aligned?

There is a very sim­ple trick to achieve this.
Wrap your but­ton in a par­ent div and give that par­ent div a style of text-align: center;

.my-btn {
  margin-left: auto;
  margin-right: auto;
}

.btn-container {
  text-align:center;
}

Take a look at this fid­dle for a work­ing example.

You may also like...