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

相关推荐
biubiubiu07066 分钟前
Chrome DevTools在Agent编程工具上的安装
前端·chrome·chrome devtools
老虎06276 分钟前
前端超全总结-----html,css,flex,vue,Ajax,ElementPlus,vueRouter语法应用讲解
前端·css·html
坚持学习前端日记15 分钟前
AgentAi视频模型开发对接部署使用
前端·人工智能·python·flask·音视频
兆子龙17 分钟前
深入探究 React 史上最大安全漏洞
前端·javascript
广州华水科技22 分钟前
单北斗GNSS形变监测在水库安全中的应用与技术优势
前端
摸鱼的春哥25 分钟前
Agent🤖记忆的提取与压缩!再也不担心我的Agent记忆混乱了
前端·javascript·后端
海石6 小时前
微信小程序开发01:XR-FRAME的快速上手
前端·增强现实·trae
叶梅树9 小时前
DocsJS npmjs 自动化发布复盘(Trusted Publisher)
前端·npm
我命由我123459 小时前
Element Plus - Form 的 resetField 方法观察记录
开发语言·前端·javascript·vue.js·html·html5·js
清空mega9 小时前
《Vue3 项目结构详解:components、views、assets、router、stores 到底该怎么理解?》
前端·javascript·vue.js