CSS两侧固定,中间自适应

这个效果,其实和一侧固定,一侧自适应是一样的原理

以下代码分别用到了 position、float、display: flex / grid、calc

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
    .box {
      border: 1px solid #000;
    }
    .box1 {
      background-color: #f00;
    }
    .box2 {
      background-color: #aee;
    }
    .box3 {
      background-color: #ccc;
    }

    /** 第一种 定位 */
    .absolute {
      position: relative;
    }
    .absolute .box1 {
      width: 200px;
      height: 300px;
      position: absolute;
      left: 0;
      top: 0;
    }
    .absolute .box2 {
      height: 200px;
      margin-left: 200px;
      margin-right: 200px;
    }
    .absolute .box3 {
      width: 200px;
      height: 300px;
      position: absolute;
      right: 0;
      top: 0;
    }

    /** 第二种 实现中间的宽度是随着文字的增加而变宽 而不是占满全部剩余空间 */
    .float .box1 {
      width: 200px;
      height: 300px;
      float: left;
    }

    .float .box2 {
      height: 100px;
      /* 加这个是为了防止文字过多将左右盒子顶下来 */
      max-width: calc(100% - 400px);
      display: inline-block;
    }

    .float .box3 {
      width: 200px;
      height: 300px;
      float: right;
    }

    /* 第三种 使用左右浮动 前两个必须是浮动的 第三个自适应 */
    .float1 .box1 {
      width: 200px;
      height: 300px;
      float: left;
    }

    .float1 .box2 {
      width: 200px;
      height: 300px;
      float: right;
    }

    .float1 .box3 {
      height: 100px;
    }

    /** 第四种 flex */
    .calc-flex {
      display: flex;
    }
    .calc-flex .box1 {
      width: 200px;
      height: 200px;
    }

    .calc-flex .box2 {
      width: calc(100% - 400px);
    }

    .calc-flex .box3 {
      width: 200px;
      height: 200px;
    }

    /** 第五种 grid */
    .grid {
      display: grid;
      grid-template-columns: 200px calc(100% - 400px) 200px;
      grid-template-rows: 300px;
    }

  </style>
</head>
<body>
<div class="box grid">
  <div class="box1"></div>
  <div class="box2">222222sssssssssssssssssssssss</div>
  <div class="box3"></div>
</div>
</body>
</html>

将对应类名,依次加到box上就能看到效果

相关推荐
砚凝霜2 分钟前
【软考信息安全】第二十二章 Web服务器安全分析与增强——Apache与IIS
服务器·前端·安全
u0111026752 小时前
JPG、PNG、WebP 怎么选?按透明度、体积和使用场景做判断
前端·javascript·vue.js·图像处理·ai作画
jerrywus2 小时前
让 AI 写完代码后交一份报告:我改造了 answer-me-with-html
前端·claude·cursor
派小心.3 小时前
小程序分享链路中来源参数的传递校验
大数据·前端·数据库·人工智能·小程序·数据分析
hhb_6183 小时前
一键生成数据看板,ECharts实战演示
前端·javascript·echarts
Java后端的Ai之路3 小时前
08_React组件API
前端·react.js·前端框架
小马不起床3 小时前
零基础玩转 FastAPI_09:前端基础工程构建
前端·状态模式·fastapi
风骏时光牛马5 小时前
用户管理模块接口开发
前端
彭亚川Allen5 小时前
从零手搓 RAG 之检索全流程,给大模型接上自己的知识库
前端·后端·ai编程
IT_陈寒5 小时前
别让Java字符串拼接偷偷吃掉你的内存
前端·人工智能·后端