Trouble using floats to mimic a table layout with different-sized objects

人盡茶涼 提交于 2019-12-25 08:42:05

问题


I'm trying to create a table-less layout using floats, but I'm having trouble getting small objects to float on both sides of larger objects. Is this possible?

Here's a visual of what I'm trying to do:

UPDATE: I'd like to be able to add new blue boxes and pink boxes at any time and anywhere in the document, and not have to apply custom floats to individual items...

I've saved the actual code on JSFiddle: http://jsfiddle.net/TuZfm/

If you prefer to see the raw code, here it is:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<style type="text/css">
.wrapper {
    width:100px;
    margin:2em auto;
    }
.box {
    height:10px;
    width:10px;
    margin:5px;
    float:left;
    background-color:blue;
    }
.box-medium {
    height:30px;
    width:30px;
    margin:5px;
    float:left;
    background-color:pink;
    }
</style>
</head>
<body>
    <div class="wrapper">
        <img class="box"/>
        <img class="box"/>
        <img class="box-medium"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
        <img class="box"/>
    </div>
</body>
</html>

Thanks for any help!

Here's what I get when I try inline-block:

It's almost perfect except for the deadspace beside the pink box... I'd like to have two rows of blue boxes beside the pink box.

Here's the code I used when trying inline-block: http://jsfiddle.net/QCAFM/


回答1:


If you want to be able to add new elements on the fly, you should consider using a javascript solution for this problem.

Here's a good one. http://masonry.desandro.com/




回答2:


float: right on the small boxes, and float: left on the large one. Worked here




回答3:


Have you considered using display: inline-block; instead of floats? Seems to work fine for me.




回答4:


You could use a combination of absolute positioning on the pink box (taking the box out of the flow, so it won't affect the floating blue boxes), and jQuery (to add the necessary space). This solution will only work however, if the pink box is the 3rd child.

http://jsfiddle.net/yjmdz/

EDIT: this seems to be working only on Chrome, I'm still figuring out what's happening..



来源:https://stackoverflow.com/questions/8592774/trouble-using-floats-to-mimic-a-table-layout-with-different-sized-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!