CSS-两栏布局

112 阅读1分钟

实现方案

左侧固定宽度,右侧自适应

  1. 左侧float:left, 右侧 margin-left:left-width
  2. 左侧float:left, 右侧生成 BFC
  3. 左侧position:absolute, 右侧 margin-left: left-width
  4. 弹性flex布局

示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>

    /* 1、左侧float:left + 右侧margin-left:left-width */
    /* .box1 {
      float: left;
      width: 100px;
      background-color: red;
    }
    .box2 {
      margin-left: 100px;
      background-color: green;
    } */

    /* 2、左侧float:left + 右侧 BFC */
    /* .box1 {
      float: left;
      width: 100px;
      background-color: red;
    }
    .box2 {
      background-color: green;
      overflow: auto;
    } */

    /* 3、左侧position:absolute,右侧margin-left:left:width */
    /* .container {
      position: relative;
    }
    .box1 {
      position: absolute;
      top: 0;
      left: 0;
      width: 100px;
      background-color: red;
    }
    .box2 {
      margin-left: 100px;
      background-color: green;
    } */

    /* 4、flex布局 */
    .container {
      display: flex;
    }
    .box1 {
      width: 100px;
      background-color: red;
    }
    .box2 {
      flex: 1;
      background-color: green;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="box box1">左侧内容</div>
    <div class="box box2">右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容右侧内容</div>
  </div>
</body>
</html>

image.png