My code works well if I don't set horizontal margin. This is why my code use .width() for get and set an element width, but I can't do the same with .outerWidth() because it's read-only. Is there a way to set it?
I've many buttons (using float: left) with various widths and I want to have a single width for every of them, in order to make a nice and optimized button table.
So I've written this:
buttons = $('.button-table > button');
maxWidth = Math.max.apply(
Math,
buttons.map(function(){
return $(this).width();
}).get()
);
columns = Math.floor($('#container').width()/maxWidth);
buttons.width(100/columns+'%');
This code works, but if I set an horizontal margin for the buttons, the last ones shift on the next lines.
Note: I prefer percentages because if I use this code I often see some pixels left at the right end of the container (I can see them using a different color):
buttons.width(Math.floor($('.button-table').width()/columns));
Note
This is my first question on Stack Overflow, so excuse me if I make mistakes using this platform.
Here's the solution:
No margin: http://jsfiddle.net/x33bD/2/
With margin: http://jsfiddle.net/x33bD/7/
Basically, I've added divs (using class="box") around buttons with this style:
.box {
float: left;
}
.box button {
margin-left: auto ;
margin-right: auto ;
margin-top: 5px;
margin-bottom: 5px;
display: block;
width: 90%;
white-space: nowrap;
}
This CSS could be better: it could stretch the buttons without setting the width.
The jQuery code is the same (buttons becames .box, .width() becames .outerWidth()...):
boxes = $('#container > .box');
maxWidth = Math.max.apply(
Math, boxes.map(function() {
return $(this).outerWidth();
}).get());
columns = Math.floor($('#container').width() / maxWidth);
boxes.width(100 / columns + '%');
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