I have a parent div#main
that contains unknown number of divs
in rows. Every row has 3 divs
that are display: inline-block
. Now, because of that, the last row can contain 1, 2 or 3 divs
, depending on their number.
If the last row has only 1 div, then I want do add border-left
and border-right
to it.
If the last row has 2 divs, then I want do add border-right
to the first div
in that row, or border-left
to the second div
.
And if the last row has 3 divs, then I want to add border-left
and border-right
to to the second div (the middle one).
(You'll get the full picture when you look at the snipper, or the fiddle)
I managed to solve this issue by using JS, but I'm looking for a pure CSS solution, if there is one.
$('.main').each(function(){
var div_length = $(this).find('div').length;
if((div_length % 3) === 0){
div_last_items = div_length;
}
else if((div_length % 3) === 1){
div_last_items = div_length - 1;
$(this).find('div:nth-last-child(1)').addClass('active-borders');
}
else if((div_length % 3) === 2){
div_last_items = div_length - 2;
$(this).find('div:nth-last-child(2)').addClass('active-border');
}
$(this).find('div:lt('+div_last_items+')').each(function(i){
i=i+2;
if(i % 3 === 0){
$(this).addClass('active-borders')
}
});
});
.main {
width: 360px;
text-align: center;
}
.main>div {
display:inline-block;
vertical-align:top;
width: 100px;
height: 100px;
background:red;
margin-top: 10px;
margin-bottom: 10px;
}
.main>div:nth-child(3n+2) {
margin-left: 20px;
margin-right: 20px;
}
.active-borders{
border-left: 5px solid black;
border-right: 5px solid black;
}
.active-border{
border-right: 5px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<hr>
<div class="main">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<hr>
<div class="main">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>