仅根据一个孩子调整定位元素的大小

时间:2018-03-29 12:00:35

标签: html css

我有一个带有两个孩子的绝对定位的容器。我希望容器的宽度基于第一个子节点的宽度,而第二个子节点动态地适应其父节点的宽度。



const passenger = document.getElementById("passenger");
function toggle(){
  passenger.classList.toggle("squashed");
}

#top {
  padding: 4px;
  border: thin solid red;
  position: absolute;
}

ul {
  padding: 4px;
  border: thin solid green;
}

li {
  padding: 4px;
  border: thin solid purple;
}

ul#passenger li {
  width: auto; /* ??? No good -- what goes here ??? */
}

.squashed {
  max-width: 10em;
}

<button onclick="toggle()">Toggle</button>
<hr/>
<div id="top">
  <ul id="driver">
    <li>This is the desired width</li>
  </ul>
  <ul id="passenger">
    <li>This should be forced to wrap because its width doesn't contribute to the container width calculation.</li>
  </ul>
</div>
&#13;
&#13;
&#13;

点击&#34;切换&#34;示例中的按钮可以看到我想要的效果的近似值。当我不人为地限制passenger的宽度时,它会水平增长以填充页面,这会推动top的宽度以匹配它。

我已尝试设置#passenger li {width:auto;}以及width:100%;,以及word-wrap等的各种组合,但我无法弄清楚如何强制{{1获取其父级的宽度。似乎li仅在明确设置#passenger li {width:100%;}的宽度时才有效,而不是基于top的宽度。它也&#34;工作&#34;如果我driverpassenger完全排除在流position: absolute之外我想要的方式,但我希望top完全包含这两个元素,所以这不是一个选项。

仅使用CSS(没有JS)可以达到预期的效果吗?

1 个答案:

答案 0 :(得分:0)

您可以在父元素上使用display: table和一些小宽度(例如1%)执行此操作,然后在第一个white-space: nowrap元素上设置ul

在这种情况下,所有其他子元素都会将其宽度调整为最大值。

&#13;
&#13;
#top {
  padding: 4px;
  border: thin solid red;
  position: absolute;
  display: table;
  width: 1%;
}
#driver {
  white-space: nowrap;
}
ul {
  padding: 4px;
  border: thin solid green;
}
li {
  padding: 4px;
  border: thin solid purple;
}
&#13;
<div id="top">
  <ul id="driver">
    <li>This is the desired width</li>
  </ul>
  <ul id="passenger">
    <li>This should be forced to wrap because its width doesn't contribute to the container width calculation.</li>
  </ul>
</div>
&#13;
&#13;
&#13;