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. css : center element vertically and horizontally
  2. Using css3 calc in an attribute value to compute its value at runtime
  3. Making max width work in internet explorer
  4. Applying floats and clearfix to block elements
  5. How to set a box shadow on left or right only or just on a single slide
  6. simple css reset
  7. css - circular profile pictures
  8. pseudo elements vs pseudo classes