flex-shrink如何赢得填充?

时间:2017-07-08 15:03:57

标签: html css css3 flexbox

我有一个从外面调整大小的弹性框标签云。我希望它内部的标签可以折叠,如果需要可以折叠到零(边缘情况)。现在,它们只能达到填充量的2倍。

Image

基本上,我需要一种方法来flex-shrink"赢得"反对padding

如果可能的话,我想在不使用overflow:hidden的情况下实现这一点,因为这会干扰此机箱内的其他内容。

Runnable片段:



$('button').on('click', (e) => {
  $('.tags').css({
    width: $(e.target).text()
  });
});

.tags {
  display: flex;
  margin-bottom: 20px;
  background: red;
  overflow: visible;
  padding: 20px 5px;
}
.tag {
  position: relative;
  padding: 5px 10px;
  background: #ccc;
  border: 1px solid #aaa;
  border-radius: 20px;
  white-space: nowrap;
  text-overflow: ellipsis;
  flex-shrink: 1;
  overflow: hidden;
}
.tag + .tag {
  margin-left: 3px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Tags will not collapse beyond 2 x padding</h3>
<div class="tags" style="width: 200px">
  <div class="tag">Tag 1</div>
  <div class="tag">Tag 2</div>
  <div class="tag">Tag 3</div>
</div>
<br />
<div>
  <button>200px</button>
  <button>100px</button>
  <button>50px</button>
  <button>10px</button>
</div>
&#13;
&#13;
&#13;

有人有想法吗?

1 个答案:

答案 0 :(得分:2)

flex-shrink无法胜过填充,普通的阻止元素也不会:fiddle demo

实现这项工作的一种方法是为文本添加一个额外的包装器,并在其上设置填充/边框而不是flex项。

&#13;
&#13;
$('button').on('click', (e) => {
  $('.tags').css({
    width: $(e.target).text()
  });
});
&#13;
.tags {
  display: flex;
  margin-bottom: 20px;
  background: red;
  overflow: visible;
  padding: 20px 5px;
}
.tag {
  flex-shrink: 1;
  overflow: hidden;
}
.tag div {
  padding: 5px 10px;
  background: #ccc;
  border: 1px solid #aaa;
  border-radius: 20px;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.tag + .tag {
  margin-left: 3px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Tags will not collapse beyond 2 x padding</h3>
<div class="tags" style="width: 200px">
  <div class="tag"><div>Tag 1</div></div>
  <div class="tag"><div>Tag 2</div></div>
  <div class="tag"><div>Tag 3</div></div>
</div>
<br />
<div>
  <button>200px</button>
  <button>100px</button>
  <button>50px</button>
  <button>10px</button>
</div>
&#13;
&#13;
&#13;