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

相关推荐
恋恋风尘hhh1 小时前
滑动验证码前端安全研究:以顶象(dingxiang-inc)为例
前端·安全
懂懂tty8 小时前
React状态更新流程
前端·react.js
小码哥_常8 小时前
告别繁琐!手把手教你封装超实用Android原生Adapter基类
前端
skywalk81638 小时前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
一只蝉nahc9 小时前
vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息
前端·vue.js·unity
子兮曰9 小时前
Bun v1.3.12 深度解析:新特性、性能优化与实战指南
前端·typescript·bun
2401_8858850410 小时前
易语言彩信接口怎么调用?E语言Post实现多媒体数据批量下发
前端
a11177610 小时前
Three.js 的前端 WebGL 页面合集(日本 开源项目)
前端·javascript·webgl
Kk.080210 小时前
项目《基于Linux下的mybash命令解释器》(一)
前端·javascript·算法
小李子呢021111 小时前
前端八股---闭包和作用域链
前端