根据 width/size 对多个 Flexbox 行中的元素进行排序

Sort elements in multiple Flexbox rows according to their width/size

假设我有一组这样的列表项(某种类别):

ul.categoryList {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 180px;
}

ul.categoryList > li {
  list-style: none;
}
<ul class="categoryList">
  <li>Literature</li>
  <li>Science Fiction and Fantasy</li>
  <li>Harry Potter</li>
  <li>Movies and Films</li>
  <li>Books</li>
</ul>

而这个 <ul> 位于带有 max-width<div> 中,如果调整 window 的大小或在不同的 resolution/devices(手机,平板电脑,...)。

如您所见,某些列表项比其他项长。假设此 <ul> 的容器只能包含列表项 Science Fiction and Fantasy 和更多,因此下一项将转到下一行,因为它不适合同一行。

正如您可能看到的那样,问题是 LiteratureBooks 可能在同一行,但由于它们不连续,它们最终会分开行,其他项目也是如此。

因此,我没有将一些最短的项目放在一起以减少行数,而是得到 5 行(实际上每个项目一行),这 space 消耗。

有什么办法可以解决这个问题吗?可以用 CSS 完成还是我需要 JavaScript?

按字符数对元素排序

您需要使用 JavaScript 根据元素的 length/size 对元素进行排序。

这是一个使用 Array.prototype.sort() to sort them according to the number of characters of each of them (Node.innerText 的基本示例):

// Sort the elements according to their number of characters:

const categoryList = document.getElementById('categoryList');

Array.from(categoryList.children).sort((a, b) => {
  const charactersA = a.innerText.length;
  const charactersB = b.innerText.length;
  
  if (charactersA < charactersB) {
    return -1;
  } else if (charactersA === charactersB) {
    return 0;
  } else {
    return 1;
  }
}).forEach((element) => {
  // When appending an element that is already a child, it will not
  // be duplicated, but removed from the old position first and then
  // added to the new one, which is exactly what we want:
  
  categoryList.appendChild(element);
});
#categoryList {
  font-family: monospace;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 220px;
  border-right: 2px solid #000;
}

#categoryList > li {
  background: #000;
  color: #FFF;
  padding: 4px 8px;
  margin: 0 4px 4px 0;
  border-radius: 2px;
}
<ul id="categoryList">
  <li>Literature</li>
  <li>Science Fiction and Fantasy</li>
  <li>Harry Potter</li>
  <li>Movies and Films</li>
  <li>Books</li>
</ul>

按实际宽度对元素进行排序

innerText 可能适用于 monospaced 字体,但对于其他字体,您可以使用 HTMLElement.offsetWidth 来考虑元素的实际宽度:

/**
* Get the actual width of an element, taking into account margins 
* as well:
*/
function getElementWidth(element) {
  const style = window.getComputedStyle(element);
  
  // Assuming margins are in px:
  return element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight);
}


// Sort the elements according to their actual width:

const categoryList = document.getElementById('categoryList');

Array.from(categoryList.children).sort((a, b) => {
  const aWidth = getElementWidth(a);
  const bWidth = getElementWidth(b);
  
  if (aWidth < bWidth) {
    return -1;
  } else if (aWidth === bWidth) {
    return 0;
  } else {
    return 1;
  }
}).forEach((element) => {
  // When appending an element that is already a child, it will not
  // be duplicated, but removed from the old position first and then
  // added to the new one, which is exactly what we want:
  
  categoryList.appendChild(element);
});
#categoryList {
  font-family: monospace;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 220px;
  border-right: 2px solid #000;
}

#categoryList > li {
  background: #000;
  color: #FFF;
  padding: 4px 8px;
  margin: 0 4px 4px 0;
  border-radius: 2px;
}
<ul id="categoryList">
  <li>Literature</li>
  <li>Science Fiction and Fantasy</li>
  <li>Harry Potter</li>
  <li>Movies and Films</li>
  <li>Books</li>
</ul>

排序元素最小化空space

您还可以实施自定义排序算法,以不同的方式对它们进行排序。例如,您可能希望最小化每一行的空 space:

/**
* Get the actual width of an element, taking into account margins 
* as well:
*/
function getElementWidth(element) {
  const style = window.getComputedStyle(element);
  
  // Assuming margins are in px:
  return element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight);
}

/**
* Find the index of the widest element that fits in the available
* space:
*/
function getBestFit(elements, availableSpace) {
  let minAvailableSpace = availableSpace;
  let bestFitIndex = -1;
  
  elements.forEach((element, i) => {
    if (element.used) {
      return;
    }
    
    const elementAvailableSpace = availableSpace - element.width;
    
    if (elementAvailableSpace >= 0 && elementAvailableSpace < minAvailableSpace) {
      minAvailableSpace = elementAvailableSpace;
      bestFitIndex = i;
    }
  });
  
  return bestFitIndex;
}

/**
* Get the first element that hasn't been used yet.
*/
function getFirstNotUsed(elements) {
  for (let element of elements) {
    if (!element.used) {
      return element;
    }
  }
}


// Sort the elements according to their actual width:

const categoryList = document.getElementById('categoryList');
const totalSpace = categoryList.clientWidth;
const items = Array.from(categoryList.children).map((element) => {
  return {
    element,
    used: false,
    width: getElementWidth(element),
  };
});
const totalItems = items.length;

// We want to keep the first element in the first position:
const firstItem = items[0];
const sortedElements = [firstItem.element];

firstItem.used = true;

// We calculate the remaining space in the first row:
let availableSpace = totalSpace - firstItem.width;

// We sort the other elements:
for (let i = 1; i < totalItems; ++i) {
  const bestFitIndex = getBestFit(items, availableSpace);
  
  let item;
  
  if (bestFitIndex === -1) {
    // If there's no best fit, we just take the first element
    // that hasn't been used yet to keep their order as close
    // as posible to the initial one:
    item = getFirstNotUsed(items);
    availableSpace = totalSpace - item.width;
  } else {
    item = items[bestFitIndex];
    availableSpace -= item.width;
  }
  
  sortedElements.push(item.element);  
  item.used = true;
}

sortedElements.forEach((element) => {
  // When appending an element that is already a child, it will not
  // be duplicated, but removed from the old position first and then
  // added to the new one, which is exactly what we want:
  
  categoryList.appendChild(element);
});
#categoryList {
  font-family: monospace;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 220px;
  border-right: 2px solid #000;
}

#categoryList > li {
  background: #000;
  color: #FFF;
  padding: 4px 8px;
  margin: 0 4px 4px 0;
  border-radius: 2px;
}
<ul id="categoryList">
  <li>Literature</li>
  <li>Science Fiction and Fantasy</li>
  <li>Harry Potter</li>
  <li>Movies and Films</li>
  <li>Books</li>
</ul>

✨ 让它看起来更好

最后,在对列表中的每个 child 进行排序以删除它们之间的任何不规则空 space 之后,您可以将 flex: 1 0 auto 应用于列表中的每个 child:

/**
* Get the actual width of an element, taking into account margins 
* as well:
*/
function getElementWidth(element) {
  const style = window.getComputedStyle(element);
  
  // Assuming margins are in px:
  return element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight);
}

/**
* Find the index of the widest element that fits in the available
* space:
*/
function getBestFit(elements, availableSpace) {
  let minAvailableSpace = availableSpace;
  let bestFitIndex = -1;
  
  elements.forEach((element, i) => {
    if (element.used) {
      return;
    }
    
    const elementAvailableSpace = availableSpace - element.width;
    
    if (elementAvailableSpace >= 0 && elementAvailableSpace < minAvailableSpace) {
      minAvailableSpace = elementAvailableSpace;
      bestFitIndex = i;
    }
  });
  
  return bestFitIndex;
}

/**
* Get the first element that hasn't been used yet.
*/
function getFirstNotUsed(elements) {
  for (let element of elements) {
    if (!element.used) {
      return element;
    }
  }
}


// Sort the elements according to their actual width:

const categoryList = document.getElementById('categoryList');
const totalSpace = categoryList.clientWidth;
const items = Array.from(categoryList.children).map((element) => {
  return {
    element,
    used: false,
    width: getElementWidth(element),
  };
});
const totalItems = items.length;

// We want to keep the first element in the first position:
const firstItem = items[0];
const sortedElements = [firstItem.element];

firstItem.used = true;

// We calculate the remaining space in the first row:
let availableSpace = totalSpace - firstItem.width;

// We sort the other elements:
for (let i = 1; i < totalItems; ++i) {
  const bestFitIndex = getBestFit(items, availableSpace);
  
  let item;
  
  if (bestFitIndex === -1) {
    // If there's no best fit, we just take the first element
    // that hasn't been used yet to keep their order as close
    // as posible to the initial one:
    item = getFirstNotUsed(items);
    availableSpace = totalSpace - item.width;
  } else {
    item = items[bestFitIndex];
    availableSpace -= item.width;
  }
  
  sortedElements.push(item.element);  
  item.used = true;
}

sortedElements.forEach((element) => {
  // When appending an element that is already a child, it will not
  // be duplicated, but removed from the old position first and then
  // added to the new one, which is exactly what we want:
  
  categoryList.appendChild(element);
});

// If you want to add a class to make the elements inside the list
// expand, you have to do it after sorting them. Otherwise, they would
// already take all available horizontal space and the sorting algorithm
// won't do anything:
categoryList.classList.add('expand');
#categoryList {
  font-family: monospace;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 220px;
  border-right: 2px solid #000;
}

#categoryList > li {
  background: #000;
  color: #FFF;
  padding: 4px 8px;
  margin: 0 4px 4px 0;
  border-radius: 2px;
}

#categoryList.expand > li {
  flex: 1 1 auto;
}
<ul id="categoryList">
  <li>Literature</li>
  <li>Science Fiction and Fantasy</li>
  <li>Harry Potter</li>
  <li>Movies and Films</li>
  <li>Books</li>
</ul>