首页 > 解决方案 > 如何使容器宽度依赖于特定子项的宽度?

问题描述

我有一个div带有多个孩子(也是divs)的容器。我需要底部的孩子与里面的文本宽度相同。父容器和其他子容器的宽度应该与底部子容器的宽度完全相同,即底部子容器决定了所有东西的宽度。我该如何做到这一点?

我怀疑 flexbox 可能会有所帮助,但我无法在文档中找到任何相关内容。甚至可以用纯 CSS 来完成,还是我必须为此使用 JavaScript?

这是一个演示问题的小提琴

<div class="parent">
  <div class="slave">Child that shouldn't dictate the width to anybody at all even though it's long</div>
  <br>
  <div class="master">Child that dictates the width to the parent and siblings</div>
</div>

它能做什么:

在此处输入图像描述

我想要的(省略号是不必要的,如果它只是切断就可以了):

在此处输入图像描述

标签: htmlcssflexbox

解决方案


用 div 包裹 slave 的文本并将其放在绝对位置。当文本太长时添加树点应用text-overflow: ellipsis

.parent {
  background-color: green;
  display: inline-block;
}

.slave {
  background-color: blue;
  color: red;
  width: auto;
  height: 40px;
  position: relative;
}

.slave div {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;

  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.master {
  background-color: red;
  color: black;
  width: auto;
  height: 40px;
}
<div class="parent">
  <div class="slave">
    <div>Child that shouldn't dictate the width to anybody at all even though it's long</div>
  </div>
  <br>
  <div class="master">Child that dictates the width to the parent and siblings</div>
</div>


<div class="parent">
  <div class="slave">
    <div>Two words</div>
  </div>
  <br>
  <div class="master">Child that dictates the width to the parent and siblings</div>
</div>


推荐阅读