html - 如果内容溢出div中指定的宽度和高度,则水平和垂直滚动条
问题描述
#myleft {
float: left;
width: 20%;
position: relative;
}
#myRight {
float: left;
width: 80%;
position: relative;
}
.displayBox {
float: left;
width: 33%;
position: relative;
height: 60px;
overflow: auto;
}
<div>
<div id="myLeft">
<h4>Left Content</h4>
</div>
<div id="myRight">
<div class="displayBox">
<p>Display the first content on BOX 1</p>
</div>
<div class="displayBox">
<p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
</div>
<div class="displayBox">
<p>Display the first content on BOX 3</p>
</div>
<div class="displayBox">
<p>Display the first content on BOX 4 and horizontal scroll bar</p>
</div>
</div>
<div>
myRight div中可能有三个或更多div。我希望同一行上的所有 div 不会溢出到水平滚动的下一行。对于内容溢出,我指定了每个 div 的高度为 60px 和 overflow:auto,这给了我垂直滚动条。同样,如果有 3 个以上的 div,我想要水平滚动。
解决方案
而不是使用float
,你可以使用display: flex
。
display: flex
block
并排对齐子项(类似于float
)。添加flex: 0 0 auto;
到这些孩子中会阻止它们包装。
要显示水平滚动条,您可以使用overflow-x: auto;
.
.container {
display: flex;
}
#myLeft {
width: 20%;
}
#myRight {
width: 80%;
display: flex;
overflow-x: auto;
}
.displayBox {
width: calc(100% / 3); /* to achieve perfect thirds */
flex: 0 0 auto;
height: 60px;
overflow: auto;
}
<div class="container">
<div id="myLeft">
<h4>Left Content</h4>
</div>
<div id="myRight">
<div class="displayBox">
<p>Display the first content on BOX 1</p>
</div>
<div class="displayBox">
<p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
</div>
<div class="displayBox">
<p>Display the first content on BOX 3</p>
</div>
<div class="displayBox">
<p>Display the first content on BOX 4 and horizontal scroll bar</p>
</div>
</div>
</div>
推荐阅读
- android - Jetpack compose 打破 Room 编译器
- php - Codeigniter 计数 2 个表之间的关联记录
- javascript - React js - 将值传递给孩子到父母到另一个孩子
- sql - 如何将非唯一数据加载到主键 SQL
- reactjs - getDerivedStateFromProps 有什么用(或者你如何解雇它?)
- html - 如何将输入框对齐 2 行
- ms-access-2016 - MS Access 如何使用 Query 或 VBA 获取 4 位序列的所有组合的计数
- ansible - 如果服务器上不存在磁盘 sdb,我如何显示类似“磁盘不存在”的消息
- npm - 安装 Vue CLI 时缺少写入权限
- python - 在 Python 中从 CSV 文件创建混合图表