Julez
Julez

Reputation: 1369

Float left elements do not stack

I have a problem with some floating elements. What I want is when you resize the browser window that box 3 is right under box 1

HTML:

<div class="box">
    <p>box 1</p>
    <p>box 1</p>
    <p>box 1</p>
</div>
<div class="box">
     <p>box 2</p>
    <p>box 2</p>
    <p>box 2</p>
    <p>box 2</p>
    <p>box 2</p>
</div>
<div class="box">
     <p>box 3</p>
    <p>box 3</p>
    <p>box 3</p>
</div>

CSS:

.box {
    width:80px;
    float:left;
    border:1px solid slateGrey;
    margin:0 0 0 10px;
    padding:10px;
}

See Fiddle: Fiddle

I tried something with the clear property but nothing helps.

Upvotes: 1

Views: 75

Answers (3)

Nekkoru
Nekkoru

Reputation: 1165

This is expected CSS behavior. If you resize the browser window while you have the fiddle open, box 3 appears under box 1. If you want box 3 to appear like that at all times, you need to add something like this .clear class:

.clear{
  clear: left;
}

You'll notice that box 3 will appear in the correct place, but a bit lower, just under box 2's bottom border. Because all of the boxes are floated, they are treated by CSS as if they were on one line, that line being as tall as the tallest .box. When you introduce a box that's .cleared, it will appear under that line. You can adjust the position using margin-top, for example change the <div> element of box 3 to:

<div class="box clear" style="margin-top: -70px;">

Hope this helped.

EDIT: Oh, also: if you want this to be dynamically added whenever there's no room to display all three boxes side-by-side, figure out how much space you need for the three boxes to be together on one line and then use a media query, like this:

@media all and (max-width: 500px){
    .box.clear{
      clear: left;
      margin-top: -70px;
    }
  }

500px being your required space. I would recommend against using this if the contents of your boxes are going to be changed a lot.

Upvotes: 0

YD1m
YD1m

Reputation: 5895

You can do this dynamic layout only with js. For example with masonry plugin.

Upvotes: 3

pcalcao
pcalcao

Reputation: 15965

If you want to control the layout when you resize the browser and hit certain dimensions, you should probably look into media queries.

http://en.wikipedia.org/wiki/Media_queries

There is a lot of material out there about the subject, so I'm just linking wikipedia for reference.

Upvotes: 0

Related Questions