如何实现两栏布局,右侧自适应?三栏布局中间自适应呢?
Interactive CSS Grid Generator | Layoutit Grid grid布局
双栏布局非常常见,往往是以一个定宽栏和一个自适应的栏并排展示存在
实现思路也非常的简单:
- 使用 float 左浮左边栏
- 右边模块使用 margin-left 撑出内容块做内容展示
- 为父级元素添加BFC,防止下方元素飞到上方内容
<style> .box{ overflow: hidden; 添加BFC } .left { float: left; width: 200px; background-color: gray; height: 400px; } .right { margin-left: 210px; background-color: lightgray; height: 200px; } </style> <div class="box"> <div class="left">左边</div> <div class="right">右边</div> </div>
实现三栏布局中间自适应的布局方式有:
- 两边使用 float,中间使用 margin
- 两边使用 absolute,中间使用 margin
- 两边使用 float 和负 margin
- display: table 实现
- flex实现
- grid网格布局
两边使用 float,中间使用 margin 需要将中间的内容放在html结构最后,否则右侧会臣在中间内容的下方 实现代码如下: <style> .wrap { background: #eee; overflow: hidden; <!-- 生成BFC,计算高度时考虑浮动的元素 --> padding: 20px; height: 200px; } .left { width: 200px; height: 200px; float: left; background: coral; } .right { width: 120px; height: 200px; float: right; background: lightblue; } .middle { margin-left: 220px; height: 200px; background: lightpink; margin-right: 140px; } </style> <div class="wrap"> <div class="left">左侧</div> <div class="right">右侧</div> <div class="middle">中间</div> </div>
原理如下:
- 两边固定宽度,中间宽度自适应。
- 利用中间元素的margin值控制两边的间距
- 宽度小于左右部分宽度之和时,右侧部分会被挤下去
这种实现方式存在缺陷:
-
主体内容是最后加载的。
-
右边在主体内容之前,如果是响应式设计,不能简单的换行展示
两边使用 absolute,中间使用 margin
基于绝对定位的三栏布局:注意绝对定位的元素脱离文档流,相对于最近的已经定位的祖先元素进行定位。无需考虑HTML中结构的顺序
<style> .container { position: relative; } .left, .right, .main { height: 200px; line-height: 200px; text-align: center; } .left { position: absolute; top: 0; left: 0; width: 100px; background: green; } .right { position: absolute; top: 0; right: 0; width: 100px; background: green; } .main { margin: 0 110px; background: black; color: white; } </style> <div class="container"> <div class="left">左边固定宽度</div> <div class="right">右边固定宽度</div> <div class="main">中间自适应</div> </div>
两边使用 float 和负 margin
<style> .left, .right, .main { height: 200px; line-height: 200px; text-align: center; } .main-wrapper { float: left; width: 100%; } .main { margin: 0 110px; background: black; color: white; } .left, .right { float: left; width: 100px; margin-left: -100%; background: green; } .right { margin-left: -100px; /* 同自身宽度 */ } </style> <div class="main-wrapper"> <div class="main">中间自适应</div> </div> <div class="left">左边固定宽度</div> <div class="right">右边固定宽度</div>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库