004-CSS-左右经典布局

本文详细介绍了五种网页布局技巧:弹性盒子布局、绝对定位配合padding/margin、行内块布局使用calc、浮动与BFC。每种方法都有适用场景和Tips,帮助开发者理解和选择合适的布局方式。

方案一:弹性盒子布局

💡 Tips:左侧子盒子宽度固定,右侧子盒子 flex: 1

.parent {
  display: flex;
  width: 500px;
  height: 300px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-bottom: 20px;
}
.left-son {
  width: 100px;
  height: 100%;
  background: #4a90e2;
}
.right-son {
  flex: 1;
  height: 100%;
  background: #dfffdf;
}

方案二:绝对定位 + padding

💡 Tips:父盒子相对定位,padding-left,左侧子盒子绝对定位

.parent {
  position: relative;
  padding-left: 100px;
  width: 500px;
  height: 300px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-bottom: 20px;
}
.left-son {
  position: absolute;
  left: 0;
  width: 100px;
  height: 100%;
  background: #4a90e2;
}
.right-son {
  height: 100%;
  background: #dfffdf;
}

方案三:绝对定位 + margin

💡 Tips:父盒子相对定位,左侧子盒子绝对定位,右侧子盒子margin-left

.parent {
  position: relative;
  width: 500px;
  height: 300px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-bottom: 20px;
}
.left-son {
  position: absolute;
  left: 0;
  width: 100px;
  height: 100%;
  background: #4a90e2;
}
.right-son {
  margin-left: 100px;
  height: 100%;
  background: #dfffdf;
}

方案四:行内块布局 + calc

💡 Tips:父盒子font-size: 0,子盒子行内块,左侧子盒子100px,右侧子盒子 calc(100% - 100px)

.parent {
  font-size: 0; /* 解决DOM换行引起的空白像素问题 */
  width: 500px;
  height: 300px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-bottom: 20px;
}
.left-son {
  display: inline-block;
  vertical-align: top;
  width: 100px;
  height: 100%;
  background: #4a90e2;
}
.right-son {
  display: inline-block;
  vertical-align: top;
  width: calc(100% - 100px);
  height: 100%;
  background: #dfffdf;
}

方案五:浮动 + BFC

💡 Tips:左侧子盒子浮动,右侧盒子 overflow:hidden; 触发 BFC

.parent {
  width: 500px;
  height: 300px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  margin-bottom: 20px;
}
.left-son {
  float: left;
  width: 100px;
  height: 100%;
  background: #4a90e2;
}
.right-son {
  overflow: hidden;
  height: 100%;
  background: #dfffdf;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值