DonFuchs
DonFuchs

Reputation: 133

Min-height of list to fit at least n list items with plain CSS

I have some kind of header div containing a list with a dynamic number of items, and I want the header height to be fixed; if there are too many list items the ul will overflow the header if hovered (or else only the last 2 items are shown), that's already taking care of:

https://jsfiddle.net/te5cykdn/11/

function fill(n) {
  let ul = document.getElementsByTagName("ul")[0];
  ul.innerHTML = "";

  for (let i = 0; i < n; i++) {
    let li = document.createElement("li");
    li.innerHTML = i;
    ul.appendChild(li);
  }
}
html,
body {
  height: 100%;
}

div {
  height: 50px;
  border: 2px solid black;
}

ul {
  list-style-type: none;
  padding: 5px;
  margin: 0;
  position: relative;
}

ul:hover {
  overflow-y: visible;
  z-index: 1;
}

li {
  text-align: center;
}

ul>li:hover {
  color: white;
  cursor: pointer;
}

ul:not(:hover)>li:nth-last-child(n+3) {
  display: none;
}

ul>li:nth-child(even) {
  background-color: red;
}

ul>li:nth-child(odd) {
  background-color: blue;
}
<button onclick="fill(1)">1 item</button>
<button onclick="fill(2)">2 items</button>
<button onclick="fill(3)">3 items</button>
<button onclick="fill(4)">4 items</button>

<div>
  <ul></ul>
</div>

But how do I set a fixed height on the header without hard-coding px, rather something like: fixed height to fit at least 2 list items, say, using plain CSS, no JavaScript?

So again, I know how to fix the height; my question is how to do it without setting fixed pixel height.

Upvotes: 1

Views: 518

Answers (1)

Temani Afif
Temani Afif

Reputation: 273086

You can consider setting line-height for your li elements and use the same value as a multiplier:

function fill(n) {
  let ul = document.getElementsByTagName("ul")[0];
  ul.innerHTML = "";

  for (let i = 0; i < n; i++) {
    let li = document.createElement("li");
    li.innerHTML = i;
    ul.appendChild(li);
  }
}
html,
body {
  height: 100%;
}

div {
  height: calc(var(--n)*1.2em);
  border: 2px solid black;
  padding: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding:0;
  position: relative;
}

ul:hover {
  overflow-y: visible;
  z-index: 1;
}

li {
  text-align: center;
  line-height:1.2em;
}

ul>li:hover {
  color: white;
  cursor: pointer;
}

ul:not(:hover)>li:nth-last-child(n+3) {
  display: none;
}

ul>li:nth-child(even) {
  background-color: red;
}

ul>li:nth-child(odd) {
  background-color: blue;
}
<button onclick="fill(1)">1 item</button>
<button onclick="fill(2)">2 items</button>
<button onclick="fill(3)">3 items</button>
<button onclick="fill(4)">4 items</button>

<div style="--n:2">
  <ul></ul>
</div>

Upvotes: 1

Related Questions