Be the first user to complete this post
|
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:
- simple css reset
- center using css
- Applying floats to inline elements
- Understanding the CSS 3 transition property syntax
- css specificity interview question