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:
- position:absolute
- Using css3 calc in an attribute value to compute its value at runtime
- Two column layout in css
- css: margin does not work
- center using css