Search code examples
htmlcssrow

Wrapping div to new line causing funny behavior


If any of the nested divs below have a length longer then an adjacent div, the divs don't wrap to the next line "properly".

Without dividing each row in it's own div, is there a way to force div #5 (in the example below) to fall underneath div #1 even if div #1 is taller than the rest?

<style type="text/css">
  .video-item {
    margin: 10px 29px 20px 0px;
    width: 208px;
    float: left;
    overflow: hidden;
  }
</style>

<div style="width: 948px;">
  <div class="video-item">1<br>This is what happens when Description is too long... </div>
  <div class="video-item">2<br>Description</div>
  <div class="video-item">3<br>Description</div>
  <div class="video-item">4<br>Description</div>
  <div class="video-item">5<br>Description</div>
  <div class="video-item">6<br>Description</div>
  <div class="video-item">7<br>Description</div>
  <div class="video-item">8<br>Description</div>
  <div class="video-item">9<br>Description</div>
  <div class="video-item">10<br>Description</div>
</div>

Example with even Description:
Example with even Description

Example with uneven Description:
Example with uneven Description


Solution

  • You need to set the clear CSS style on the div, to bring it back into normal flow:

    <style type="text/css">
        .video-item {
            margin: 10px 29px 20px 0px; 
            width: 208px; 
            float: left;
            overflow: hidden; 
        }
        .clear {
            clear: left;
        }
    </style>
    
    <div style="width: 948px;">
        <div class="video-item">1<br>This is what happens when Description is too long...         </div>
        <div class="video-item">2<br>Description</div>
        <div class="video-item">3<br>Description</div>
        <div class="video-item">4<br>Description</div>
        <div class="video-item clear">5<br>Description</div>
        <div class="video-item">6<br>Description</div>
        <div class="video-item">7<br>Description</div>
        <div class="video-item">8<br>Description</div>
        <div class="video-item clear">9<br>Description</div>
        <div class="video-item">10<br>Description</div>
    </div>
    

    With CSS3, you could use :nth-child to achieve this more dynamically:

    .video-item:nth-child(4n+1) {
        clear: left;
    }