Skip to content

Instantly share code, notes, and snippets.

@patrickatwsrn
Last active July 19, 2021 13:25
Show Gist options
  • Save patrickatwsrn/cc65b595ee4a856c7473374fe8923a62 to your computer and use it in GitHub Desktop.
Save patrickatwsrn/cc65b595ee4a856c7473374fe8923a62 to your computer and use it in GitHub Desktop.
Display children of element in multiple columns if the number of children is equal to or higher than a certain number.

Task

Use css column count to split content of a container IF the container has more than "n" children.

Problem

There is no css selector that helps you to find elements with n or more children.

Solution

Use vanilla javascript to add column-count.

Usage

  • Add javascript to document. Should be supported by all modern browsers supporting ECMA 6+. jQuery is not required.
  • Add container with class name "multiColumn"

You might wabnt to style lists including icons in front to line up nicely.

More

Browser support

Readmore

const multiColumns = document.querySelectorAll('.multiColumn');
if(multiColumns.length > 0){
multiColumns.forEach(multiColumn => {
/* options may be changed by data-atributes */
var columnCount = multiColumn.getAttribute('data-column-count') ? multiColumn.getAttribute('data-column-count') : 2;
var columnGap = multiColumn.getAttribute('data-column.gap') ? multiColumn.getAttribute('data-column.gap') : '4rem';
/* don't change anything below this point */
var total = multiColumn.childElementCount;
console.log(total);
if(total >= 5) {
//console.log('columns enabled');
multiColumn.classList.add("multi-column-true");
multiColumn.style.columnCount = columnCount;
multiColumn.style.columnGap = columnGap;
for(let i = 0; i < multiColumn.children.length; i++){
multiColumn.children[i].style.breakInside = 'avoid';
}
}
});
}
<ul class="multiColumn">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment