第一种:采用浮动/定位的方式来实现自适应;
<!-- 方式一: 采用浮动/或者定位 -->
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
/* 定位方式 第二步 */
position: relative;
width: 100%;
height: 48px;
margin: 40px auto;
border: 4px solid steelblue;
}
.left {
/*
浮动
float: left; */
/* 定位方式 第一步 */
position: absolute;
top: 0;
left: 0;
width: 40px;
background-color: yellowgreen;
height: 100%;
}
.right {
width: 100%;
height: 100%;
background-color: pink;
padding-left: 40px;
}
</style>
<div class="box">
<div class="left">左侧</div>
<div class="right">右侧</div>
</div>
第二种方式 使用弹性布局
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
display: flex;
width: 100%;
height: 48px;
margin: 40px auto;
border: 4px solid steelblue;
}
.left {
/* 确定固定宽度 */
width: 40px;
background-color: yellowgreen;
height: 100%;
}
.right {
/* 自适应剩余宽度内容 */
flex: 1;
height: 100%;
background-color: pink;
}
</style>
第三种方式使用 网格布局
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
display: grid;
/* 表示第一列宽度为130px 第二列自适应*/
grid-template-columns: 130px auto;
width: 100%;
height: 48px;
margin: 40px auto;
border: 4px solid steelblue;
}
.left {
background-color: yellowgreen;
}
.right {
background-color: pink;
}
</style>
显然这几种方式都可以实现两列自适应 同时后两种方式也更加简单 更常用,同理也可以实现三列自适应布局,可以做一些在移动端小盒子需要确定固定宽度,而其他内容自适应大小的情况。