I have a div which can have 2 or 4 buttons based on different scenario. I want the buttons inside the div to be center aligned. How it can be done. I have submitted my code below.
<div style="margin: 0 auto; width: 656px;">
<input type="submit" style="float:left;" value="Prev"/><input type="reset" value="Reset" style="float:left;"/>
<input type="submit" value="Submit" style="float:left;"/><input style="float:left;" type="submit" value="Close"/></div>
The problem is it works when four buttons gets displayed but not for 3,2 and 1 button scenario. How to center align this without specifying width ? Plz help.
To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
You need to use text-align: center
on the container element. Also, avoid using inline styles...
<div style="margin: 0 auto; width: 656px; text-align: center;">
Demo
Note: Make sure that you use
text-align: left;
if you have any text inside thatdiv
else they will be centered as well.
As you commented, it looks like center to me
Still you are not believing that they are perfectly centered, I would tweak the containers width
and will show you that they are centered....
With 2 Buttons
Note: Make sure you use CSS Reset as well... So that you get consistent styles in all browsers though this should be centered regardless of resetting the styles.
If buttons are the only thing present in your div, then you should give text-align:center property to the div. With this everything inside the div will be center aligned not depending on the width.
<div style="margin: 0 auto; width: 656px;text-align:center;">
<input type="submit" value="Prev"/><input type="reset" value="Reset"/>
<input type="submit" value="Submit"/><input type="submit" value="Close"/>
</div>
Try this:
<div style="width:100%"><div style="margin: 0 auto; text-align: center;">
<input type="submit" value="One"/><input type="reset" value="Two"/> <input type="submit" value="Three"/><input type="reset" value="Four"/></div></div>
http://jsfiddle.net/eK22Y/10/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With