CSSHTML实现高度宽度自适应

首先说明 auto 和 100%是不一样的,100%是根据元素的像素有关的,auto是自动的。
举个例子:给box下添加一个div高度是100%,这时候div高度为box高度300px,
这时候如果给这个div设置padding,那么这个div的高度等于box的高度+padding的像素之和。

再说一个知识点:
正常文档流下,块级元素的宽度等于父元素的宽度,高度为内容撑开的高度;内联元素的高度宽度都是内容撑开的高度宽度;
设置绝对定位/固定定位/浮动会脱离文档流;
脱离文档流下,块级元素的宽度是内容撑开的元素,高度还是内容撑开的高度;
给内联元素设置绝对定位/固定定位/浮动,内联元素就会有块元素的特点。

<div class="box">
  <div class="header"></div>
  <div class="content">
    <div class="left"></div>
    <div class="main"></div>
  </div>
</div>

第一种使用:width: auto;overflow: hidden

<style>
  *{margin: 0;padding: 0;}
  .box{width:300px;height:300px;position: relative;margin: 20px auto;}
  .header{height: 100px;width: 100%;background: #FF0000;}
  .content{position: absolute;top:100px;bottom: 0;background: yellow;height: auto;width: 100%;}
  .left{float: left;height: 100%;width: 100px;background: aqua;}
  .main{background: green;overflow: hidden;width: auto;;height: 100%;}

</style>

二种使用: width: 100%;padding;box-sizing: border-box;

<style>

  *{margin: 0;padding: 0;}

  .box{width:300px;height:300px;position: relative;margin: 20px auto;}
  .header{height: 100px;width: 100%;background: #FF0000;}
  .content{position: absolute;top:100px;bottom: 0;background: yellow;height: auto;width: 100%;}
  .left{float: left;height: 100%;width: 100px;background: aqua;}
  /* .main{background: green;width: auto;height: 100%;padding-left: 100px;} */
  /* 这种情况,宽度是auto就会自己适应 */
  .main{background: green;width: 100%;height: 100%;padding-left: 100px;box-sizing: border-box;}
  /* 这个时候width是100%,是相对于父元素的宽度,padding-left属性就会是宽度多出100px,这时候就需要设置box-sizing: border-box;的作用是把padding往里加,不会改变宽度. */

</style>

猜你喜欢

转载自www.cnblogs.com/Isabella-CC/p/10085448.html
今日推荐