John
John

Reputation: 7049

Vertical list of items with gap size as percentage of item size

I have a vertical list of items of equal but implicit size. I want a gap between the items to be a percentage relative to this implicit size.

The main problem is that vertical margins are relative to widths, not heights, so they can't be used for this. (Otherwise, one could have a child in the item add the gap as a margin.)

The gap property of flex boxes and grids is in relation to the entire container.

I think this is likely impossible but I wanted to check with the community to verify.

Upvotes: 0

Views: 46

Answers (1)

alechristopher
alechristopher

Reputation: 144

I'm not sure it can be done with pure css, but here is a simple version with javascript, I just looped through a lists children and dynamically set the margin in this case as 10% of its height.

var list = document.getElementById('list');
var children = list.children;
for (var i = 0; i < children.length; i++) {
   children[i].style.marginTop = (parseInt(children[i].clientHeight) * .1).toString() + "px";
}
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
 background-color: gray;
 padding: 10px;
}

.list{
 background-color: lightgray;
 display: flex;
 flex-direction: column;
 list-style: none;
}

.list-item{
  background-color: lightblue;
}

#li1{
  height: 25px;
}
#li2{
  height: 50px;
}
#li3{
  height: 75px;
}
<div class="container">
  <ul class="list" id="list">
    <li class="list-item" id='li1'>Item 1</li>
    <li class="list-item" id='li2'>Item 2</li>
    <li class="list-item" id='li3'>Item 3</li>
  </ul>
</div>

Upvotes: 1

Related Questions