Reputation: 3323
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.
I want to clear after every 3rd item without changing the html markup, so that the 4th item goes to the next row. I'm trying to add nth-child(3):after, but does not seem to work.
Here's the code:
HTML:
<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>
CSS:
.item:nth-child(3):after{
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
Demo: http://jsfiddle.net/KPXyw/
Upvotes: 47
Views: 51507
Reputation: 1
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>
Upvotes: -1
Reputation: 2102
sabof is right. But It will be great if you use display: inline-block
instead of float:left
. Please see below for example.
.list {
width: 300px;
font-size: 0;
}
.item {
display: inline-block;
width: 90px;
font-size: 16px;
background: yellow;
margin-right: 5px;
margin-bottom: 10px;
vertical-align: top;
}
<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>
Upvotes: 1
Reputation: 5309
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.
Upvotes: -1
Reputation: 17920
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.
Upvotes: 3