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

相关推荐
m0_748229992 小时前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
C澒2 小时前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..2 小时前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
hhy_smile2 小时前
Class in Python
java·前端·python
小邓吖3 小时前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
南风知我意9573 小时前
【前端面试2】基础面试(杂项)
前端·面试·职场和发展
LJianK13 小时前
BUG: Uncaught Error: [DecimalError] Invalid argument: .0
前端
No Silver Bullet3 小时前
Nginx 内存不足对Web 应用的影响分析
运维·前端·nginx
一起养小猫4 小时前
Flutter for OpenHarmony 实战 表单处理与验证完整指南
android·开发语言·前端·javascript·flutter·harmonyos
weixin_395448914 小时前
main.c_cursor_0130
前端·网络·算法