JSFiddle - React, Tailwind, and code Playground

by Tanay861

HTML

<div class="card">
   <div class="tag">Developing</div>
   <div class="tag">DevelopersDevelopI</div>
   <div class="tag">Busniess1</div>
   <div class="tag">Web Design</div>
   <div class="tag">Web Design</div>
   <div class="tag">Web Design</div>
</div>

CSS

*,*::before,*::after {
  box-sizing: border-box;
}

.card {
  padding: 5px;
  width: 300px;
  height: 300px;
  border: 2px solid blue;
  display: flex;
  flex-direction: row;
  gap: 5px;
}

.tag {
  padding: 5px 8px;
  color: #2C3C93;
  background: rgb(44, 60, 147, 0.1);
  height: fit-content;
  white-space: nowrap;
}

JavaScript

const card = document.querySelector('.card');
const getWidth = (el) => {
 return el.getBoundingClientRect().width;
}
const widthCard = getWidth(card);
const tags = [...document.querySelectorAll('.tag')];
const totalWidth = tags.reduce((total, currentEl) => getWidth(currentEl) + total, 0);
if (totalWidth > widthCard) {
  const numberTag = document.createElement('div');
  numberTag.classList.add('tag');
  numberTag.textContent = tags.length + '+';
  card.appendChild(numberTag);
	const newElements = [];
  const remainingTags = [];
	let newTotal = getWidth(numberTag) + 19 // +19 for the padding and border and a gap;
  for (let tag of tags) {
  	const width = getWidth(tag);
    if ((newTotal + width) < widthCard) {
    	newElements.push(tag);
      newTotal += width + 5; // +5 for spacing
    } else {
    	remainingTags.push(tag);
    }
  }
  
numberTag.textContent = `${tags.length - newElements.length}+`;
   newElements.push(numberTag);
  card.innerHTML = '';
  newElements.forEach((el) => {
  	card.appendChild(el);
  })
  
  //You can use the remanining tags to show a tooltip, like this:
  numberTag.setAttribute('title', remainingTags.map(e => e.textContent).join(', '));
}