我想通过使用flexbox CSS来实现类似这样的效果。菜单是固定宽度的,但是表格可以自动增长,而标题不应超过表格宽度,即使它很长。换句话说,表格应该能够拉伸列容器,但标题不应该。
+----+--------+ |菜单| 标题 | | +--------+ | | 表格 | +----+--------+
只需一个flex列就可以轻松实现。
<html>
<style>
td {
font-size: 60px;
}
.container {
font-size: 60px;
background-color: yellow;
display: flex;
flex-direction: column;
}
.item1 {
background-color: red;
white-space: nowrap;
overflow: hidden;
}
.item2 {
background-color: blue;
}
</style>
<body>
<div class="container">
<div class="item1">Item 1 bla bla blaaas asd das dsa das das aaaaaaaaa</div>
<div class="item2">
<table>
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
</table>
</div>
</div>
</body>
</html>
但是当添加菜单后,一切都不正常,标题没有被截断。
<html>
<style>
.main {
display: flex;
}
.menu {
background-color: #222222;
width: 200px;
}
td {
font-size: 60px;
}
.container {
font-size: 60px;
background-color: yellow;
display: flex;
flex-direction: column;
width: 100%;
}
.item1 {
background-color: red;
white-space: nowrap;
overflow: hidden;
}
.item2 {
background-color: blue;
}
</style>
<body>
<div class="main">
<div class="menu">
菜单
</div>
<div class="container">
<div class="item1">Item 1 bla bla blaaas asd das dsa das das aaaaaaaaa</div>
<div class="item2">
<table>
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
所以你希望包含标题的元素能够随其兄弟元素的大小而变化,但不影响其自身的子元素。
我唯一能想到的方法是将标题文本包裹在适当的元素中 - 在这个例子中是
<span>- 然后使用position: absolute将其从流中取出,并在标题的父元素上使用position: relative。然后你需要给标题设置一些高度。示例
我用
flex: 0 0 200px替换了宽度。这将使菜单不会随着大小而变化,始终保持在200px。.main { display: flex; } .menu { background-color: #222222; flex: 0 0 200px; /*改变了*/ } td { font-size: 60px; } .container { font-size: 60px; background-color: yellow; display: flex; flex-direction: column; width: maxwidth; /*将宽度改为maxwidth*/ } .item1 { background-color: red; white-space: nowrap; overflow: hidden; position: relative; /*添加了*/ height: 1.2em; /*添加了*/ } .item1 span { position: absolute; /*添加了*/ } .item2 { background-color: blue; }<div class="main"> <div class="menu"> 菜单 </div> <div class="container"> <div class="item1"><span>The quick brown fox jumped over the lazy dog</span></div> <div class="item2"> <table> <tr> <td>数据</td> <td>数据</td> <td>数据</td> </tr> </table> </div> </div> </div>