如何使容器的宽度取决于特定孩子的宽度?

时间:2019-06-06 06:54:49

标签: html css flexbox

我有一个div容器,其中有多个子代(也有div s个)。我需要底部的子元素与其内部的文本具有相同的宽度。父容器和其他子容器的宽度应与底部容器的宽度完全相同,即底部容器确定所有物体的宽度。我该如何实现?

我怀疑flexbox可能有帮助,但是我在文档中找不到任何相关内容。甚至有可能在纯CSS中做到这一点,还是我必须使用JavaScript?

这是一个演示问题的fiddle

<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>

它的作用:

enter image description here

我想要的东西(省略号是没有必要的,只要切掉就可以了):

enter image description here

2 个答案:

答案 0 :(得分:1)

按div包裹从站的文本并将其放置为绝对。要在文本太长时添加树点,请应用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>

答案 1 :(得分:0)

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

希望这将是您解决问题的方法

相关问题