问题
On a web page, I have a row of submit buttons.
- This row of buttons should be centered on the page
- Each button should be as wide as the widest button (i.e no fixed/hard-coded button widths).
This is easily done with a <table>
, but as people keep telling me those are bad for you, I wondered if this can be done with CSS instead. So, I have tried the display: table
and table-cell
CSS classes, but either the buttons don't get equal widths, or the longest button's caption gets clipped:
.button-row {
display: table;
margin: auto;
table-layout: fixed;
}
.button-row button {
white-space: nowrap;
display: table-cell;
width: 50%;
}
<div class="button-row" >
<button>Short caption</button>
<button>A much longer caption</button>
</div>
Actually, it does look correct in IE, but not in Chrome and Firefox. Here is a fiddle with both my table- and CSS-attempt:
http://jsfiddle.net/kfwhpre8/
If possible, I would like to get rid of the width: 50%
settings, because the number of buttons may vary, but that's easy enough to calculate.
回答1:
Looking at your fiddle, keep in mind that in the table version the buttons
are contained in td
s. This is the essence of the problem. It appears using table-cell
on buttons directly is problematic. If you don't mind chaniging your HTML you can try:
<div class="button-row">
<div>
<button>Short caption</button>
</div>
<div>
<button>A much longer caption</button>
</div>
</div>
.button-row {
display: table;
margin: auto;
table-layout: fixed;
}
.button-row>div {
display: table-cell;
width: 50%;
}
.button-row button {
width:100%;
}
Fiddle
回答2:
prob not the answer you are looking for as you said you want to get rid of the width:50%
If you set the width:100%
in the button-row button{}
all the buttons will be as wide as the widest button
.button-row button {
display: table-cell;
width: 100%;
}
回答3:
I'm unsure if this would suffice, as you'd have to check each time a new button was added, as to the best size for them. But you could simply add a width to each button and a margin to replicate the table layout.
At least in the HTML's current form.
.button-row button {
display: table-cell;
width: 150px;
margin: 1px;
}
Fiddle: http://jsfiddle.net/kfwhpre8/3/
来源:https://stackoverflow.com/questions/26641652/centered-table-like-layout-with-columns-of-equal-widths-using-css