有一个具有最大和最小宽度的容器。有一个随机的标签列表。您需要在此容器中精美地排列标签,以便尽可能少的空白空间,而布局应该是流畅的。
标签的顺序并不重要。标签名称必须在 1 行中。标签宽度固定:80px;80像素*2;80像素*3;80像素*4。 主要问题是:是否可以使用 CSS Grid 解决问题,还是需要包含 JS?
下面的代码演示了这个问题 - 从给定大小创建 10 个随机长度的标签
const container = document.querySelector("#app");
for (let i = 0; i < 10; i++) {
createItem();
}
function createItem() {
const div = document.createElement("div");
div.className = "item";
const text = createText();
div.innerText = text;
const baseWidth = 79;
const baseLength = 7;
let width = baseWidth;
if (text.length > baseLength && text.length < baseLength * 2) width *= 2;
if (text.length >= baseLength * 2 && text.length < baseLength * 3) width *= 3;
if (text.length >= baseLength * 3 && text.length <= baseLength * 4)
width *= 4;
div.style.width = width + "px";
container.appendChild(div);
}
function createText() {
const str = "qwertyuiopasdfghjklzxcvbnm";
const length = Math.floor(Math.random() * (str.length / 1.5 + 1)) + 3;
return str.slice(0, length);
}
body{
display: flex;
justify-content: center;
align-items: center;
}
#app{
min-width: calc(90px * 3);
max-width: calc(90px * 6);
border: 1px solid;
display: flex;
flex-wrap: wrap;
}
.item{
padding: 5px 15px;
background-color: #F8FAFF;
border: 1px solid;
margin: 0px 5px 12px 5px;
text-align: center;
}
<div id="app"></div>
是否有可能用 CSS 解决问题?
是的你可以。
根据材料:
是的,我认为这更好
flex-grow到目前为止,我使用 JS 解决了这个问题
顺便说一句,这可以应用在本网站的“跟踪标签”块中