Centered tabular layout with equal width columns using CSS?

On a webpage, I have a row of submit buttons.

  • This row of buttons should be centered on the page
  • Each button must be as wide as the widest button (no fixed / hard-coded button width).

It's easy to do with help <table>

, but since people keep telling me it's bad for you, I wondered if it could be done with CSS. So, I've tried the CSS display: table

and classes table-cell

, but either the buttons don't get the same width, or the longest title of the button is 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>

      

Clipped button caption

Actually, it looks correct in IE, but not in Chrome and Firefox . Here is a fiddle with my attempted table and CSS:

http://jsfiddle.net/kfwhpre8/

If possible, I would like to get rid of the settings width: 50%

, because the number of buttons may differ, but this is easy enough to calculate.

0


source to share


3 answers


As you look at your fiddle, keep in mind that the tabular version buttons

contains td

s. This is the crux of the problem. It looks like using buttons table-cell

on buttons is directly problematic. If you don't mind to improve 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

+1


source


prob is not the answer you are looking for as you said you wanted to get rid of width:50%

If you set width:100%

to button-row button{}

, all buttons will be as wide as the widest button



.button-row button {
   display: table-cell;
   width: 100%;
}

      

0


source


I'm not sure if this will be enough as you will need to check every time a new button is added for the best size for them. But you can just add a width for each button and a margin to replicate the table layout.

At least in the current HTML form.

.button-row button {
    display: table-cell;
    width: 150px;
    margin: 1px;
}

      

Fiddle: http://jsfiddle.net/kfwhpre8/3/

0


source







All Articles