多个div排列在同一行而不换行
2024-09-01 03:38:55
有时候,我们可能会产生多个div标签横向排列而不换行的需求,具体有以下几种实现方法:
1. 同级div设置display:inline-block,父级div强制不换行
例如:
<html>
<head></head>
<body>
<div id="container">
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div>
</body>
<style>
#container {
width:400px;
height: 200px;
background-color: red;
overflow: auto;
white-space: nowrap;
}
.lable {
width: 100px;
background-color: blue;
display: inline-block;
}
</style>
</html>
2. 通过position绝对定位实现
例如:
<html>
<head></head>
<body>
<div id="container">
<div id="lable1">测试测试</div>
<div id="lable2">测试测试</div>
<div id="lable3">测试测试</div>
<div id="lable4">测试测试</div>
<div id="lable5">测试测试</div>
<div>
</body>
<style>
#container {
width:400px;
height: 200px;
background-color: red;
overflow: auto;
position: relative;
}
#lable1 {
width: 100px;
margin-left: 0;
background-color: blue;
position: absolute;
}
#lable2 {
width: 100px;
margin-left: 100px;
background-color: blue;
position: absolute;
}
#lable3 {
width: 100px;
margin-left: 200px;
background-color: blue;
position: absolute;
}
#lable4 {
width: 100px;
margin-left: 300px;
background-color: blue;
position: absolute;
}
#lable5 {
width: 100px;
margin-left: 400px;
background-color: blue;
position: absolute;
}
</style>
</html>
3. 通过flex方式实现
具体请参考:Flex 布局教程:语法篇
例如:
<html>
<head></head>
<body>
<div id="container">
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div class="lable">测试测试</div>
<div>
</body>
<style>
#container {
width:400px;
height: 200px;
background-color: red;
display: flex;
display: -webkit-flex;
/* 从左端开始沿水平轴防止flex item */
flex-direction: row;
/* 强制 flex item不换行,沿着同一行堆叠 */
flex-wrap: nowrap;
/* flex item在主轴上的对齐方式,这里定义左对齐 */
justify-content: flex-start;
/* 定义交叉轴对其方式 */
align-items: flex-start
}
.lable {
width: 100px;
margin-left: 5px;
background-color: blue;
}
</style>
</html>
不过,这样以来,flex容器的overflow属性将不再起作用。在flex布局下,所有的flex item均分或根据开发者定义分配容器空间,而不会超过flex容器空间。
注意
值得注意的时,如果仅仅设置父div容器的overflow属性,容器内的元素均为inline或者inline-block,也无法一直堆叠在同一行而不换行,他们无法撑开父容器。当一行无法放置下它们时间,他们会自动换行。
————————————————
版权声明:本文为CSDN博主「Kiloveyousmile」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Kiloveyousmile/article/details/80248083
最新文章
- 快速了解微信小程序的使用,一个根据小程序的框架开发的todos app
- 孙鑫MFC学习笔记14:网络编程
- Android开发中的Json字符串与复杂的嵌套对象互转。
- 批处理快速更改ip地址
- 字符识别(模板匹配&;BP神经网络训练)
- Linux上vi(vim)编辑器使用教程
- vim 分屏
- PostgreSQL的 initdb 源代码分析之十九
- UVA 11636-Hello World!(水题,猜结论)
- redis入门(15)redis的数据备份和恢复
- jenkins配置演示
- 第一个Jsp页面,基于普元EOS
- Asp.net Security框架(2)
- Nginx优化文件编写
- Eclipse搭建C++\C开发环境
- SSE图像算法优化系列二十四: 基于形态学的图像后期抗锯齿算法--MLAA优化研究。
- InnoDB中锁的算法(2)
- 微信、陌陌等著名IM软件设计架构详解(转)
- linux sticky
- ffplay源码分析2-数据结构