效果图
方法1:通过calc方法做宽度自适应
设置
width: calc(100% - 100px);
(1)这里减100px是示例中有left类名的div宽度,具体减多少px根据情况来
(2)减号两侧的空格不能少,不然识别不了
<!DOCTYPE html><html lang="en"><head><style>*{margin: 0;padding: 0;}.main{height: 300px;background: #ccc;}/* 左侧div */.left{/* 宽度固定100px */width: 100px;height: 100px;background: #b8e5ff;float: left;}/* 右侧div */.right{/* 100% - 100px(左侧盒子的宽度) */width: calc(100% - 100px);height: 100px;background: #d1ffd6;float: left;}</style></head><body><div class="main"><div class="left">Left</div><div class="right">Right</div></div></body></html>
方法2:通过弹性盒flex做自适应
父级容器设置
display: flex;
需要自适应宽度的元素设置flex: 1;
<!DOCTYPE html><html lang="en"><head><style>*{margin: 0;padding: 0;}.main{height: 300px;background: #ccc;display: flex;}/* 左侧div */.left{/* 宽度固定100px */width: 100px;height: 100px;background: #b8e5ff;float: left;}/* 右侧div */.right{flex: 1;height: 100px;background: #d1ffd6;float: left;}</style></head><body><div class="main"><div class="left">Left</div><div class="right">Right</div></div></body></html>