开发者

Position elements in a top->down left->right manner

开发者 https://www.devze.com 2023-02-09 20:25 出处:网络
I have a main container <div> which holds 4 or 5 other sub <div>s. The container has a fixed height and a fixed width. What is the best way to position the sub divs so that they are arrang

I have a main container <div> which holds 4 or 5 other sub <div>s. The container has a fixed height and a fixed width. What is the best way to position the sub divs so that they are arranged in a top->down then left->right manner?

I've tried floating the sub divs but that just gives me a left->right then top->down order.

Basically I want this

[ sub div 1][sub div 3][sub div 4]
[ sub div 2][         ][sub div 5]

When I mark up the code like this:

<div id="container">
    <div class="subdiv">sub div 1...</div>
    <div class="subdiv">sub div 2...</div>
    <div class="subdiv">sub div 3...</div>
    <div class="subdiv">sub div 4...</div>
    <div class="subdiv">sub div 5...</div>
&l开发者_如何学JAVAt;/div>

Notice that the sub divs can have variable heights but fixed widths.

Thank you,


To my knowledge, there's no way to do it.

There is some CSS3 that works only on some browsers to support multi-column layout (-moz-column-width, etc...) but I don't know whether it would work with DIVs in the content. And I'm fairly certain it it's not supported in IE7

The way I'd do it would be to break up the content into 3 columns containers

<div id="container">
    <div class='column'>
        <div class="subdiv">sub div 1...</div>
        <div class="subdiv">sub div 2...</div>
    </div>
    <div class='column'>
        <div class="subdiv">sub div 3...</div>
        <div class="subdiv">sub div 4...</div>
    </div>
    <div class='column'>
        <div class="subdiv">sub div 5...</div>
    </div>
</div>


Use this CSS on the DIVs:

display: inline-block


The only way to do this natively is to use CSS3 columns (as Damp mentioned) but there are some articles on how to achieve a similar effect with JavaScript as seen in this question. That case is actually more complicated than yours.

I'm thinking the best way to do it with JS would be to first split it evenly into column containers as Damp suggested with a best guess. This should help for those with JS disabled. Then us JS to measure heights of the subdivs and move them if the initial guess was off. Assuming you're using a server side language to generate the page, you should be able to split the columns evenly. You can probably even make a good estimation on the split by checking the length of content (assuming its text) as a heuristic for the likely height of the subdiv.

0

精彩评论

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

关注公众号