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上就能看到效果

相关推荐
阿懂在掘金37 分钟前
做命令式弹窗工具应该考虑什么——我为什么把 vue-layerx 设计成这样
前端·前端框架·函数式编程
太平洋月光1 小时前
AI 快捷指令:Cursor Rules · Commands · Skills
前端·ai编程
默_笙1 小时前
😁 LLM 不知道的事它不会说"不知道",而是会"编"——RAG 就是让它闭嘴先查资料
前端·javascript
stringwu1 小时前
用 LangGraph 落地飞书 Bug 自动修复 Agent 实践
前端
Revolution611 小时前
变量提升到底提升了什么:为什么 var 是 undefined,let 却直接报错
前端·javascript
Revolution611 小时前
本地明明正常,为什么 CI 又挂了:一次前端构建失败的排查过程
前端·前端工程化
太平洋月光1 小时前
stagewise如何结合cursor开发
前端·ai编程
前端Hardy1 小时前
JavaScript 终于又进化了!ES2026 正式发布,这些新特性你必须知道!
前端
光影少年1 小时前
react navite 页面跳转、传参、路由监听、导航栏自定义
前端·react native·react.js
黑土豆1 小时前
CSS 新特性:Container Queries 到底能解决什么痛点?
前端·css