DIV+CSS布局之左边宽度固定,右边宽度自适应

HTML结构

 <div class="parent">
      <div class="leftBox">左边宽度固定盒子</div>
       <div class="rightBox">右边宽度自适应盒子</div>
  </div>

相关CSS代码

注:以下CSS为Less写法,读者可转换成原生CSS,除清除浮动代码与本文布局有关,其余样式是为了效果展示,关联不大,读者可忽略。

// 父盒子样式
.parentStyle() {
  margin: 20px;
  background: bisque;
}
// 左盒子样式
.leftBoxStyle() {
  width: 200px;
  height: 200px;
  background: cyan;
}
// 右盒子样式
.rightBoxStyle() {
  background: #1890ff;
}
// 清除浮动
.clearFix() {
  &::after {
    display: block;
    content: "";
    clear: both;
  }
}

(1)float: left + margin-left:左盒子宽度

.parent {
  .parentStyle();
  .clearFix(); //清除浮动
  .leftBox {
    float: left;
   .leftBoxStyle();
  }
  .rightBox {
    margin-left: 200px;
    .rightBoxStyle();
  }
}

 

alt

(2)绝对定位 + margin-left:左盒子宽度

.parent {
  position: relative;
  height: 200px;//父盒子定高
 .parentStyle();
  .leftBox {
    position:absolute;
   .leftBoxStyle();
  }
  .rightBox {
    margin-left: 200px;
    .rightBoxStyle();
  }
}

 

alt

(3)利用table属性

 

.parent {
  display: table;
  width: 100%;
  .parentStyle();
  .leftBox {
    display: table-cell;
    .leftBoxStyle();
  }
  .rightBox {
    display: table-cell; //如右盒子不需与左盒子等高,可去除这句
    .rightBoxStyle();
  }
}

alt

(4)float: left + 右盒子width: calc(100% - 左盒子宽)

.parent {
  .parentStyle();
  .clearFix();
  .leftBox {
    .leftBoxStyle();
    float: left;
  }
  .rightBox {
    .rightBoxStyle();
    float: left;
    // width: calc(100% - 200px); //css写这句
    width: calc(~"100% - 200px");
  }
}

alt

(5)display: inline-block; + 右盒子width: calc(100% - 左盒子宽)

.parent {
  .parentStyle();
  .leftBox {
    .leftBoxStyle();
    display: inline-block
  }
  .rightBox {
    .rightBoxStyle();
    display: inline-block
    // width: calc(100% - 200px); //css写这句
    width: calc(~"100% - 200px");
  }
}

效果如(4)的效果图一样。

(6)overflow: auto

.parent {
  .parentStyle();
  .clearFix();
  // overflow: auto;//也可以
  .leftBox {
    .leftBoxStyle();
    float: left;
  }
  .rightBox {
    .rightBoxStyle();
    overflow: auto;
  }
}

效果如(4)的效果图一样。

(7)利用flex 左右盒子等高

.parent {
  .parentStyle();
  display: flex;
  .leftBox {
    .leftBoxStyle();
  }
  .rightBox {
    .rightBoxStyle();
    flex: 1;
  }
}

alt

最后:每种方法都有其适用之处,读者可根据需求自行选择。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值