Get element to use the maximum width available depending on how many instances of the element there are
Say I have an unknown amount of elements, and I wanted to expand them like so:
开发者_开发百科1 element:
[========]
2 elements:
[===][===]
3 elements:
[===][===]
[========]
4 elements:
[===][===]
[===][===]
and so on, the [===]
s being elements.
To add to the oddness of this question, the page will only ever be viewed within webkit, so -webkit elements are completely allowed even if they don't have -moz equivalents.
Is there a CSS only way of solving this problem? If not, is there a JS-minimal way of solving this problem?
Assuming markup something like this:
<div class="container">
<div>1</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
This will produce the layout you want:
.container div {
float: left;
width: 50%;
}
.container div:last-child:nth-child(2n+1) {
width: 100%;
}
Basically it says make the width 50%, but when there's an odd numbered last child make it 100%. Here's a complete example.
You can do it easly with JQuery. Something like:
$(".container").each(
function(index,item) {
if (index>0) {
var prev = $(item).prev();
if (prev.width() >= $(item).width()) {
var width = $(prev).width()/2
$(prev).width(width);
$(item).width(width);
}
}
}
);
Where "container" is the class name of this elements.
精彩评论