How to make buttons stretch equally to fill container <div> (Act like a table row with cells)

George picture George · Nov 23, 2012 · Viewed 46.9k times · Source

Let's say I have a container <div> with some buttons in:

<div class="cont">
    <div class="button">Button 1</div>
    <div class="button">Button 2</div>
    <div class="button">Button 3</div>
    <div class="button">Button 4</div>
    <div style="clear:both"></div>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

And assigned some CSS to this:

.cont{
    background:#0F0;
    width:400px;
    height:40px;
    line-height:40px;
}
.button{
    background:#F00;
    float:left;
    height:inherit;
    line-height:inherit;
}

Background colours are just so that I can see what I am doing. I'm wondering if there is a JavaScript-free way to make all of the button <div>s stretch (with equal widths) to the parent <div> and I want them to automatically get the width using the parent <div>. So, yes I could just set the .button width to 25% because there are 4 of them but if I added more buttons I would want them to automatically get a new width.

I hope I explained myself well enough, I did look around but couldn't find anything to suit this. Can I do this in CSS or is it a JS-job?

JSFiddle here.

Thanks.

Answer

Andy picture Andy · Nov 23, 2012

It can be done with display: table; and display: table-cell;

I know the bad connotations that come with tables but you aren't using table markup, you are just making div's act like tables.

See demo here

<div class="cont">
    <div class="button">Button 1</div>
    <div class="button">Button 2</div>
    <div class="button">Button 3</div>
    <div class="button">Button 4</div>
</div>​

.cont{
    background:#0F0;
    width:400px;
    height:40px;
    line-height:40px;
    display: table;
}
.button{
    background:#F00;
    display: table-cell;
}
​