简体   繁体   中英

Clearing Floats after x divs automatically with jQuery? - e.g. Varying heights break design

Ok, for my inner content i've got, for example a 4 x column layout - float left, set width... so they sit nicely next to each other...

Trouble is you add more elements into that set eg a 5th or 6th element (eg a new row) - ...if the first 4 columns are varying heights the the second row is all misaligned, as you would expect... So I'm writing to ask, is there a jQuery way (Or possibly something else) - That will allow you too add a "clear:both" after x amount of divs within a div (In this case clear the row after 4 divs)... Alot of the content will be pulled automatically from DB, so I don't have the option to manually add a clear:both.

Hope that makes sense, this is my first post, so please advise if i've done anything wrong, or can explain better.

$('div:nth-of-type(4n)').append('<div style="clear:both;"></div>');

那是你需要的吗?

You can do this responsively without JS by switching to using display: inline-block instead of floats.

http://codepen.io/cimmanon/pen/dwbHi

.gallery {
  margin: -10px 0 0 -10px;
  overflow: hidden;
}

.gallery img {
  margin: 10px 0 0 10px;
  display: inline-block;
  vertical-align: text-top;
}

  <div class="gallery">
    <img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/200x120" /><!--
    --><img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/200x140" /><!--
    --><img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/200x130" /><!--
    --><img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/200x100" /><!--
    --><img src="http://placehold.it/180x100" /><!--
    --><img src="http://placehold.it/200x90" />
  </div>

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