div+css 两列布局,一边宽度固定,一边自适应宽度
封面图
•
2025-12-24
•
Html/Css
291
0
0
0
在使用 **HTML + CSS** 实现 **两列布局**,其中一列宽度固定,另一列自适应宽度,可以通过多种方式实现。下面是常见的几种方法: --- ### ✅ 方法一:使用 `flexbox` 布局(推荐) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>两列布局</title> <style> .container { display: flex; } .left { width: 200px; /* 固定宽度 */ background-color: #f0f0f0; } .right { flex: 1; /* 自适应宽度 */ background-color: #e0e0e0; } </style> </head> <body> <div class="container"> <div class="left">左侧固定宽度</div> <div class="right">右侧自适应宽度</div> </div> </body> </html> ``` --- ### ✅ 方法二:使用 `grid` 布局(现代推荐) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>两列布局</title> <style> .container { display: grid; grid-template-columns: 200px 1fr; /* 第一列固定,第二列自适应 */ } .left { background-color: #f0f0f0; } .right { background-color: #e0e0e0; } </style> </head> <body> <div class="container"> <div class="left">左侧固定宽度</div> <div class="right">右侧自适应宽度</div> </div> </body> </html> ``` --- ### ✅ 方法三:使用 `float` 布局(传统方法) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>两列布局</title> <style> .left { width: 200px; float: left; background-color: #f0f0f0; } .right { margin-left: 200px; /* 与左侧宽度一致 */ background-color: #e0e0e0; } </style> </head> <body> <div class="left">左侧固定宽度</div> <div class="right">右侧自适应宽度</div> </body> </html> ``` > 注意:使用 `float` 布局时,建议对父容器进行清除浮动(如使用 `overflow: hidden` 或 `clearfix`)。 --- ### ✅ 方法四:使用 `table-cell` 布局(较少使用) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>两列布局</title> <style> .container { display: table; width: 100%; } .left { display: table-cell; width: 200px; background-color: #f0f0f0; } .right { display: table-cell; background-color: #e0e0e0; } </style> </head> <body> <div class="container"> <div class="left">左侧固定宽度</div> <div class="right">右侧自适应宽度</div> </div> </body> </html> ``` --- ### 总结 | 方法 | 优点 | 缺点 | |------------|---------------------------|-----------------------| | `flexbox` | 简单、灵活、兼容性好 | 旧浏览器支持有限 | | `grid` | 强大、适合复杂布局 | 旧浏览器支持有限 | | `float` | 兼容性好 | 布局复杂、容易出错 | | `table-cell` | 简单易用 | 不够灵活 | --- 如果你需要更详细的说明或有其他需求(比如响应式设计、居中对齐等),欢迎继续提问!
上一篇:
鸡肉粥
下一篇:
使用meta标签renderer指定双核浏览器以IE浏览器内核渲染网页
标题录入,一次不能超过6条
留言
评论