写一个三栏布局,中间固定,两边自适应(平均)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三栏布局</title>
    <style>
        body {
            margin: 0; /* 去除默认外边距 */
        }
        .container {
            display: flex;
            height: 100vh; /* 示例高度,可根据需要调整 */
        }
        .left, .right {
            flex: 1; /* 自适应宽度,平均分配剩余空间 */
            background-color: lightblue; /* 示例背景颜色 */
        }
        .center {
            width: 300px; /* 固定宽度 */
            background-color: lightcoral; /* 示例背景颜色 */
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left">左侧</div>
        <div class="center">中间</div>
        <div class="right">右侧</div>
    </div>
</body>
</html>

解释:

  • display: flex;: 将容器设置为 flex 布局。
  • flex: 1;: 让左侧和右侧的 div 平均分配剩余空间。 flex: 1;flex-grow: 1; flex-shrink: 1; flex-basis: 0; 的简写。
    • flex-grow: 1;:允许项目扩展以填充可用空间。由于左右两栏都设置为 1,它们会平均分配剩余空间。
    • flex-shrink: 1;:允许项目收缩以防止溢出。
    • flex-basis: 0;:初始主尺寸为 0,以便 flex-grow 生效。
  • width: 300px;: 设置中间 div 的固定宽度。
  • height: 100vh;: 设置容器高度为视口高度,只是一个示例,可以根据需要调整。
  • 去除默认外边距: body { margin: 0; } 去除了 body 的默认外边距,避免布局错乱。

其他方案 (使用 Grid 布局):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三栏布局</title>
    <style>
        body {
            margin: 0;
        }
        .container {
            display: grid;
            grid-template-columns: 1fr 300px 1fr; /* 1fr 表示剩余空间的比例 */
            height: 100vh;
        }
        .left {
            background-color: lightblue;
        }
        .center {
            background-color: lightcoral;
        }
        .right {
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left">左侧</div>
        <div class="center">中间</div>
        <div class="right">右侧</div>
    </div>
</body>
</html>

Grid 布局的 grid-template-columns: 1fr 300px 1fr; 更简洁地定义了三列的宽度。1fr 表示剩余空间的比例,因此左右两列会平分剩余空间。

选择哪种方案取决于你的具体需求和项目上下文。 Flexbox 通常更灵活,而 Grid 在处理二维布局时更强大。 这两个方案都能实现你想要的三栏布局。

posted @ 2024-12-12 09:25  王铁柱6  阅读(80)  评论(0)    收藏  举报