简体   繁体   中英

Is there a way to float a DIV4 under first DIV1 of same class when DIV1's height is slightly bigger than of DIV2 and DIV3?

I know it's difficult to understand the problem from the title, so I will explain it in real example.

  1. The server generates DIVs with contents and sends to the browser.
  2. Each DIV has same class: eg. ' .column '.
  3. All DIVs have "almost" same height. One can be slightly taller or shorter than the other.

The goal is to force FLOAT:left all columns even if the first column above is taller than its siblings. See the below screenshot.

屏幕截图

In the above image you can see that Col4 is NOT under Col1 because Col1's height is taller than its siblings'. Is there a way to force Col4 DIV be floated left under Col1 DIV?

I'm looking for a native CSS solution if possible. And I don't need simple solution like creating 3 columns and pushing DIVs into each one.

If it's really impossible, I would really appreciate if you could answer why Col6 is not "sticking" up to Col1 ?

The above can be obtained from:

.col{
  float:left;
  height:50px;
  width:130px;
  border-left: 1px solid;
  border-bottom: 1px solid;
}

.col1{
  height:60px
}

And HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div class="col col1">Col1</div>
  <div class="col">Col2</div>
  <div class="col">Col3</div>
  <div class="col">Col4</div>
  <div class="col">Col5</div>
  <div class="col">Col6</div>
</body>
</html>

Here is the live example in jsbin.

I would really appreciate any help.

You should simply be able to clear the floats:

.col:nth-child(4) {
  clear: left;
}

If you need to support older browsers, use this selector instead:

.col1 + .col + .col + .col {
  clear: left;
}

If you need your 5th and 6th columns to be flush with the bottom borders of your 2nd and 3rd columns respectively, though, you can't achieve it with floats alone. You'll need to find another way around it, or use something like jQuery Masonry to lay out your page.

The only possible reason why your 6th column isn't sticking up to your 1st column is because it's wrapping to a new line, and according to the float model a box cannot be higher than the bottom of its preceding floated boxes.

you may simply try to remove " float:left; " from you " col " class on your css and replace it with " display:inline-block; " and it may work. Not sure if it works on all browsers. Have only tried this on chrome and mozilla.

 .col{
     /*float:left;*/
     height:50px;
     width:130px;
     border-left: 1px solid;
     border-bottom: 1px solid;

     display:inline-block; 
  }

live example at http://jsbin.com/ajikoq/11/edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM