html - 如何使容器宽度依赖于特定子项的宽度?
问题描述
我有一个div
带有多个孩子(也是div
s)的容器。我需要底部的孩子与里面的文本宽度相同。父容器和其他子容器的宽度应该与底部子容器的宽度完全相同,即底部子容器决定了所有东西的宽度。我该如何做到这一点?
我怀疑 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>
它能做什么:
我想要的(省略号是不必要的,如果它只是切断就可以了):
解决方案
用 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>
推荐阅读
- ios - 升级到 MacOS Catalina 10.15 后尝试从 Xcode 11.1 部署到设备时,FIPS 出现两个错误
- javascript - 如何拦截 WKWebView 请求以检测哪些本地资源文件(css、js、png、...)与 HTML 文件一起加载?
- angular - 从商店的多个切片中获取 NGRX 数据的最佳方式是什么
- html - 使用 flexbox (justify-content: space-between/around) 属性创建导航栏时如何避免右侧出现额外空间
- r - ggplot的方面标题中的部分斜体
- sql-server - 有没有办法使用窗口函数来保持最小总数为 0 而不必有一个循环?
- html - 在 reactjs 中使用 jquery 在表中添加新行
- php - 使用 $id 路由或 Codeigniter 中的所有数据
- function - 无法从函数中插入 std::map
- python - 在时间序列中找到相似的子序列?