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.
To make a group of buttons span entire width of the screen, use the . btn-group-justified.
The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely.
Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.
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;
}
This is a perfect use case of the CSS Flexible Box Model.
HTML5 Rocks has a nice introduction to this.
This needs vendor prefixes and it's not supported on old browsers. There's Flexie which is a polyfill for older browsers.
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