I encountered a requirement to implement a style that displayed an indefinite number of labels in a row in a container of fixed width, and the length of each label was also variable. When a label cannot be fully displayed, it is not displayed. The general effect is as follows: only one row of labels is displayed. If there are too many labels, it will not be displayed.
The DOM structure of the tag part is as follows
<div class="labels">
<span class="label">Cooking</span>
<span class="label">Coding</span>
<span class="label">Travel</span>
<span class="label">Photography</span>
<span class="label">Reading</span>
</div>
Copy the code
At first glance this problem is very simple, in line with the style problem as far as possible not JS to solve the principle, wrote the following pile of styles, perfect implementation effect. Labels are folded to the next line because they exceed the width of.labels, and then hidden by overflow: hidden of.labels.
.label { display: block; height: 24px; line-height: 24px; padding: 0 10px; background-color: #e1ecf4; border-radius: 12px; font-size: 14px; flex-shrink: 0; &+. Label {margin-left: 5px; } } .labels { height: 24px; // The height of the label overflow: hidden; display: flex; flex-wrap: wrap; justify-content: flex-start; }Copy the code
If the length of the first tag exceeds the width of the container, it will not be hidden entirely, but the content will be truncated, as follows
This question has puzzled me for a while, wondering what property in CSS can hide the entire child element if it exceeds the width of the parent container (instead of just the part that exceeds the parent container). When I was about to give up and decide whether to implement js or not, I suddenly came up with the idea that since the folded element can be hidden, I should fold the first tag as well.
The first element is not the first element, but the first element is not the first element.label
Before the element, add one.placeholder
The element is only 1px wide and 100% tall. The Inspect element shows that it does.placeholder
The element takes up the first row, which is what we want
Using this idea, you can do the same thing with float. IO /Simona_Deng/codepen/codepen /…