开发者

Get element to use the maximum width available depending on how many instances of the element there are

开发者 https://www.devze.com 2023-02-12 17:09 出处:网络
Say I have an unknown amount of elements, and I wanted to expand them like so: 开发者_开发百科1 element:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号