CSS Clear after every nth-child

后端 未结 7 918
执念已碎
执念已碎 2020-12-13 12:36

I have multiple items with same width inside a container. Because of different heights of the elements, there is problem with the alignment, you can see in image below.

相关标签:
7条回答
  • 2020-12-13 12:56

    try this its working

    .list{
        width: 300px;
        overflow: hidden;
    }
    
    .item{
       float: left;
        width: 90px;
        background: yellow;
        margin-right: 5px;
        margin-bottom: 10px;
    }
    
    .item:nth-child(4){
        //background: brown;
        clear:both;
    }
    

    these only need.

    0 讨论(0)
  • 2020-12-13 13:00

    You should use nth-child(3n+1) so that it happens at each child following a child multiple by 3, not only at the first 3rd child.

    Then, you should remove that :after, you want to clear the actual child.

    0 讨论(0)
  • 2020-12-13 13:02

    Actually it's

    .item:nth-child(3n+1){
        clear:left
    }
    
    0 讨论(0)
  • 2020-12-13 13:02

    Use below code

    .item:nth-child(4){clear:both;}
    
    0 讨论(0)
  • 2020-12-13 13:04

    You can use:

    .list {
      display:flex;
      flex-wrap: wrap;
      ...
    }
    

    See below:

    .list {
      width: 300px;
      overflow: hidden;
      display: flex;
      flex-wrap: wrap;
    }
    .item {
      float: left;
      width: 90px;
      background: yellow;
      margin-right: 5px;
      margin-bottom: 10px;
    }
    .item:nth-child(3) {
      background: brown;
    }
    .item:nth-child(3):after {
      content: ".";
      display: block;
      height: 0;
      clear: both;
      visibility: hidden;
    }
    <div class="list">
      <div class="item">Lorem ipsum dolor sit amet,</div>
      <div class="item">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
      <div class="item">Lorem ipsum dolor sit amet,</div>
      <div class="item">Lorem ipsum dolor sit amet,</div>
      <div class="item">Lorem ipsum dolor sit amet</div>
    </div>

    0 讨论(0)
  • 2020-12-13 13:06
    .item:nth-child(3n+1){
        clear:left
    }
    

    Updated Fiddle

    0 讨论(0)
提交回复
热议问题