CSS实现两边固定中间自适应的方法

tech2025-08-17  4

效果如下

利用flex布局 <div class="box"> <div class="left">left</div> <div class="center">center</div> <div class="right">right</div> </div> .box{ display: flex; justify-content: space-between; } .right,.left{ flex: 0 0 200px; background: rgb(0, 255, 55);; } .center{ flex: 1; background-color: aqua } 利用定位 <div class="box"> <div class="left">left</div> <div class="center">center</div> <div class="right">right</div> </div> .box{ width: 100%; position: relative; } .right{ width: 200px; background-color: rgb(0, 255, 55); position: absolute; right: 0; top: 0; } .left{ width: 200px; background-color: rgb(0, 255, 106); position: absolute; left: 0; top: 0; } .center{ background-color: aqua } 浮动 <div class="box"> <div class="left">left</div> <div class="center">center</div> <div class="right">right</div> </div>

方法一:向同方向浮动,利用calc(100% - 400px)计算中间部分宽度

.left{ width: 200px; float: left; background-color: rgb(0, 255, 106); } .center{ width: calc(100% - 400px); float: left; background-color: aqua; } .right{ width: 200px; float: left; background-color: rgb(0, 255, 55); }

方法二:左右浮动,中间自适应

.left{ width: 200px; float: left; background-color: rgb(0, 255, 106); } .center{ background-color: aqua; } .right{ width: 200px; float: right; background-color: rgb(0, 255, 55); } 利用margin(圣杯布局和双飞翼布局)

方法一:圣杯布局

<div class="box"> <div class="center">center</div> <div class="left">left</div> <div class="right">right</div> </div> .box{ padding: 0 200px; } .center{ width: 100%; float: left; background-color: aqua; } .left{ width: 200px; float: left; margin-left: -100%; position: relative; left: -200px; background-color: rgb(0, 255, 106); } .right{ width: 200px; float: left; margin-left: -200px; position: relative; right: -200px; background-color: rgb(0, 255, 55); }

方法二:双飞翼布局

<div class="box"> <div class="center"> <div class="content">center</div> </div> <div class="left">left</div> <div class="right">right</div> </div> .center{ width: 100%; float: left; background-color: aqua; } .left{ width: 200px; float: left; margin-left: -100%; background-color: rgb(0, 255, 106); } .right{ width: 200px; float: left; margin-left: -200px; background-color: rgb(0, 255, 55); }
最新回复(0)