Centered table-like layout with columns of equal widths using CSS?

こ雲淡風輕ζ 提交于 2020-01-07 05:01:28

问题


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 tds. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!