Be the first user to complete this post

  • 0
Add to List

How to horizontally center a flexible width button using only css

Ever had to horizontally center a button only to find that unless you give it a fixed width, it wont center align. For example, it is not uncommon to find the below code being used to horizontally align a button.

.my-btn {
  width: 200px;
  margin-left: auto;
  margin-right: auto;
}
Well, although the above will work in some cases, you're better off(at least in terms of internationalization) when you allow your buttons to be of a flexible width. But then, how do you let it be horizontally aligned? There is a very simple trick to achieve this. Wrap your button in a parent div and give that parent 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 fiddle for a working example.



Also Read:

  1. Understanding the CSS 3 transition property syntax
  2. Making max width work in internet explorer
  3. center using css
  4. css - vertically align text
  5. css - align text to an image vertically