Reputation: 14866
I am trying to find a way with CSS to evenly space list items vertically.
I want each list item to have a fixed height that doesn't change. I want the margin in between each list item to automatically strecth so it has the same amount of space but margin:auto; is not working.
Here is snippet:
.container {
border: 1px solid black;
height: 500px;
width: 400px;
}
.spaced {
padding: 0;
list-style: none;
}
.spaced li {
border: 1px solid blue;
height: 60px;
margin: 15px;
}
<div class="container">
<ul class="spaced">
<li>item </li>
<li>item </li>
<li>item </li>
<li>item </li>
</ul>
</div>
So with this snippet I need it so the blue boxes will remain the same height and be spaced evenly vertically. If the black box changes in height then the blue boxes will still be evenly spaced.
How can I do this?
Upvotes: 5
Views: 6140
Reputation: 1528
You can do this using jQuery.
Here is the updated css,
.container {
border: 1px solid black;
height: 500px;
width: 400px;
}
.spaced {
padding: 0;
list-style: none;
margin:0; //Additional
}
.spaced li {
border: 1px solid blue;
height: 60px;
margin: 15px;
width: 370px; //Additional
float:left; //Additional
}
Js code is below,
function setLiMargin(){
var parentH = $(".container").height();
var liCount = $(".container ul li").length;
var liHeight = 60;
var margin = parseInt((parentH/liCount - liHeight)/2);
$('.spaced li').css('margin',margin+'px 15px');
}
$(document).ready(function(){
setLiMargin();
});
Upvotes: 0
Reputation: 122037
You can do this with Flexbox and justify-content: space-around;
Flex items are evenly distributed so that the space between two adjacent items is the same. The empty space before the first and after the last items equals half of the space between two adjacent items.
.container {
border: 1px solid black;
height: 500px;
width: 400px;
padding: 10px;
box-sizing: border-box;
}
.spaced {
height: 100%;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
justify-content: space-around;
margin: 0;
}
.spaced li {
border: 1px solid blue;
height: 60px;
}
<div class="container">
<ul class="spaced">
<li>item </li>
<li>item </li>
<li>item </li>
<li>item </li>
</ul>
</div>
Upvotes: 3
Reputation: 115045
Flexbox can do that:
.container {
border: 1px solid black;
height: 500px;
width: 400px;
}
.spaced {
padding: 0;
margin: 0;
height: 100%;
list-style: none;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.spaced li {
border: 1px solid blue;
height: 60px;
margin-left: 15px;
margin-right: 15px;
}
<div class="container">
<ul class="spaced">
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
Upvotes: 1