左栏固定,右栏自适应的两栏布局
第一种方法:采用绝对定位+BFC(overflow:auto)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .left{ width: 200px; height: 200px; background: red; position: absolute; } .right{ height: 200px; margin-left: 200px; background: blue; overflow: auto; } </style> </head> <body> <div class="left">左边</div> <div class="right">右边</div> </body> </html>
第二种方法:采用左浮动+BFC(overflow:auto)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .left{ width: 200px; height: 200px; background: red; float: left; } .right{ height: 200px; background: blue; overflow: auto; } </style> </head> <body> <div class="left">左边</div> <div class="right">右边</div> </body> </html>
第三种方法:采用flex布局+BFC(overflow:auto)(推荐使用)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .main{ display: flex; } .left{ width: 200px; height: 200px; background: red; } .right{ height: 200px; background: blue; flex: 1; overflow: auto; } </style> </head> <body> <div class="main"> <div class="left">左边</div> <div class="right">右边</div> </div> </body> </html>
第四种:table布局(高度会自动撑开)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .main { display: table; width: 100%; } .left ,.right { display:table-cell; height:240px; } .right{ background-color: blue; } .left { width: 300px; background-color: red; } </style> </head> <body> <div class="main"> <div class="left" >左边</div> <div class="right" >右边</div> </div> </body> </html>
第五种:grid网格布局+BFC(overflow:auto)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .main { display: grid; width: 100%; grid-template-rows: 200px; /*设置行高*/ grid-template-columns: 200px auto; /*设置列数属性*/ } .right{ background-color: blue; } .left { background-color: red; overflow: auto; } </style> </head> <body> <div class="main"> <div class="left" >左边</div> <div class="right" >右边</div> </div> </body> </html>
如果不触发BFC,如果右边内容超出右边盒子的高度会出现内容往左边靠和溢出的情况
第一种情况:浮动
第二种情况:绝对定位,flex布局,grid网格布局