skip to Main Content

I would like to layout unicode glyphs similar to this:

There could be anywhere from 13 to say 100 items in the displayed collection (alphabets, abjads, abugidas, syllabaries, etc..), so could have a set with 99 items, or one with 16 items, etc..

How can you most beautiful (and automatically) layout the elements (so that it is also nice when responsive)? Here is what I have by default with flexbox:

enter image description here

Each item has a fixed height, and the width is responsive (but the same for each element).

The goal is to have every row have either an even number, or an odd number, of items. This way all vertical columns will line up (and it won’t do what my animated gif is doing, where even/odd rows are intermingled).

  1. Is it possible to do some math formula to calculate something like "you need to 5 items per row, except the last row will have 3 (or 1)"? Given some total count like 99?

How would you maybe do that?

I have a React component which does the Flexbox layout like <Grid minWidth={96} gap={8} maxColumns={5} breakpoints={[5, 3, 1]} />, where breakpoints are the number of items allowed per row, and maxColumns is the max columns (breakpoints/maxColumn is kinda redundant, you can define either or, maybe I’ll clean that up later). All this info might be irrelevant, but just pointing out just in case, it’s my responsive grid component.

How can I somehow divide my total by x to figure out if it should be even or odd rows, and then set the maxColumns or breakpoints to whatever will be "most compact"? So for example:

  • If it’s 26 elements, it would look best as 6 rows of 4, followed by 1 row of 2. – If it’s 27 elements,

The "beauty" of it might be subjective, and there’s not a clear rule for what is most beautiful. Just looking for anything that doesn’t easliy leave an orphaned single node at the end and then have 7 items on all other rows. Ideally we have:

  • Between 3 and 7 columns.
  • Last row must have the same number of items in all previous rows, or no less than maxRowCount - 2 (so if all rows have 7, the last row can have 5 or 7 only, or if all rows have 5, then the last row can have 3 or 5 only, etc.).
  • Row item has a minWidth: 96px, and grows to fill the space. I can figure out how to make things responsive once we get the basics of this working, but assume a containerWidth exists.

So in my head, say we have containerWidth === 700px. Then, 700/96 == 7+, so perhaps 7 per row. If we have 99 items (for example), then 99 % 7 == 1, so 7 won’t work because we’ll have 1 in the last row. 6 won’t work because 99 is even, so try 5? 99 % 5 == 4, that won’t work because 4 is even. So try 3, 99 % 3 == 0, so that would work as is, use that!

How would you implement something like that?

2

Answers


  1. Chosen as BEST ANSWER

    Something like this seems correct, but did I solve it properly?

    console.log(
      99,
      calculateColumns({ totalCount: 99, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      98,
      calculateColumns({ totalCount: 98, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      97,
      calculateColumns({ totalCount: 97, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      96,
      calculateColumns({ totalCount: 96, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      95,
      calculateColumns({ totalCount: 95, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      94,
      calculateColumns({ totalCount: 94, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      93,
      calculateColumns({ totalCount: 93, itemWidth: 96, containerWidth: 700 })
    );
    console.log(
      91,
      calculateColumns({ totalCount: 91, itemWidth: 96, containerWidth: 700 })
    );
    
    function calculateColumns({ totalCount, itemWidth, containerWidth }) {
      let max = Math.min(Math.floor(containerWidth / itemWidth), 7)
      while (max > 3) {
        const maxIsEven = isEven(max)
        const remainder = totalCount % max
        const remainderIsEven = isEven(remainder)
        if (maxIsEven && remainderIsEven) {
          const diff = max - remainder
          if (diff <= 2) {
            return max
          }
        } else if (!maxIsEven && (!remainderIsEven || !remainder)) {
          const diff = max - remainder
          if (diff <= 2) {
            return max;
          }
        } else {
          // one is even, one is odd
        }
        max--
      }
      return max
    }
    
    function isEven(n) {
      return n % 2 === 0
    }


  2. Here is an example that repeatedly tests if the number of columns matches your criteria

    const ranges = [ 
      [0x2600, 0x26FF], // Symbols
      [0x2700, 0x27BF], // Dingbats
      [0x1F300, 0x1F5FF] // Symbols and Pictographs
    ];
    
    const randomUnicodeGlyph = () => {
      const range = ranges[Math.floor(Math.random() * ranges.length)];
      const codePoint = Math.floor(range[0] + Math.random() * (range[1] - range[0] + 1));
      return String.fromCodePoint(codePoint);
    };
    
    // Generate a set of random Unicode glyphs
    const generateGlyphSet = (length) => Array.from({ length }, randomUnicodeGlyph);
    
    // Calculate the best number of columns per row
    const calculateColumns = (totalItems, minItemWidth, containerWidth) => {
      const minColumns = 3;
      const maxColumns = 7;
      let possibleColumns = Math.min(Math.floor(containerWidth / minItemWidth), maxColumns);
    
      for (let columns = possibleColumns; columns >= minColumns; columns--) {
        let rows = Math.floor(totalItems / columns);
        let lastRowItems = totalItems % columns;
    
        if (lastRowItems === 0 || lastRowItems >= (columns - 2)) {
          return columns;
        }
      }
      return minColumns; // fallback
    };
    
    // HTML table for the glyph set
    const createTable = (glyphSet, containerWidth, minItemWidth) => {
      const columns = calculateColumns(glyphSet.length, minItemWidth, containerWidth);
      return `
          <table class="glyph-table">
            <tr>${glyphSet.map((glyph, index) => 
              `<td>${glyph}</td>${(index + 1) % columns === 0 && (index + 1 !== glyphSet.length) ? '</tr><tr>' : ''}`
            ).join('')}
            </tr>
          </table><hr/>`;
    };
    
    // Generate three sets of glyphs with random lengths between 13 and 100
    const sets = [
      generateGlyphSet(16),
      generateGlyphSet(26),
      generateGlyphSet(99)
    ];
    
    const containerWidth = 700;
    const minItemWidth = 96;
    document.body.innerHTML = sets.map(set => createTable(set, containerWidth, minItemWidth)).join('');
    .glyph-table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 20px;
    }
    
    .glyph-table td {
      height: 96px;
      text-align: center;
      font-size: 24px;
      padding: 3px;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search