When the CSS element to achieve wide can not be fully displayed to hide

Starting in my blog varnull.cn

Meet a demand, style container is required to achieve a fixed width in the row number display label, a variable number, the length of each tag is not given. When a label is not to be displayed is not fully displayed next. Effect substantially as follows, only appearing in a row, a plurality of fit is not shown.
image description

Tag of the DOM structure 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>

At first glance this question is very simple thing, as far as possible in line with the principle of no js style problem solving, and wrote the following this pile of style, perfect to achieve results. The last two can be seen .labeldue to the exceed the .labelswidth, is folded to the next line, and then again .labelsthe overflow: hiddenhidden.

.label {
    display: block;
    height: 24px;
    line-height: 24px;
    padding: 0 10px;
    background-color: #e1ecf4;
    border-radius: 12px;
    font-size: 14px;
    flex-shrink: 0; // label 不收缩,长度为内容长度

    & + .label {
        margin-left: 5px;
    }
}

.labels {
    height: 24px; // 一行 label 的高度
    overflow: hidden;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

But just happy not long, suddenly I found the problem, if the length of a label on beyond the width of the container, it will not be the entire hidden, but the content is cut off, like the following
image description

This problem has troubled me for a moment of time, there have been thinking about what css property can be in the child element width over its entire parent container to hide (not just hidden part beyond the parent container). All kinds of thinking are not ready to give a positive result in the end very tangled when not js implemented, 突然冒出来一个想法the elements are wrapped == Now that can be hidden away, so that the first label that also fold line is not on the line Well ==.

So how to make the first label wrap it, think of a way to trick the comparison, it is no longer the first element can take advantage of the characteristics flex wrap it up - so, in all .labelprior elements, add a .placeholderelement only 1px width, height of 100%.
Inspect element if indeed you can see .placeholderthe elements occupy the position of the first row, to achieve the effect we want -

image description

In fact, the use of this idea, using float the same effect can be achieved. Although a little trick and also by means of an extra DOM elements, but the effect is still the perfect realization of ~ attach codepen links for reference https: //codepen.io/Simona_Den ...

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12059494.html