美文网首页
02-布局中margin和padding区别

02-布局中margin和padding区别

作者: Threejs开发者 | 来源:发表于2018-06-20 16:07 被阅读0次

需求:
1)上下两个盒子固定定位,中间的盒子自适应高度。撑大剩余盒子高度。


Snipaste_2018-06-20_16-07-12.png

注意:
1)中间的盒子只能使用padding让出位置,并且要增加box-sizing属性。
2)marging不能达到该效果。

个人分析:
不能使用maging,因为margin先让出位置,但让出的位置还是属性剩余高度,仍然 作为自己的高度。于是就溢出来。完整代码如下:

<!-- 
  需求:
     1)上下两个盒子固定定位,中间的盒子自适应高度。撑大剩余盒子高度。
  
  注意:
     1)中间的盒子只能使用padding让出位置,并且要增加box-sizing属性。
     2)marging不能达到该效果。
 -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  
  <style>
      html,body{
        height: 100%;
      }

      .box{
        width: 500px;
        height: 100%;
        background-color: #ccc;
      }
      .box1{
        position: fixed;
        top:0px;
        left:0px;
        width: 100%;
        height: 100px;
        background-color: red;
      }

      .box2{
        height: 100%;
        background-color: yellow;
        /* 不能使用maging,因为margin先让出位置,但让出的位置还是属性剩余高度,仍然作为自己的高度。
           于是就溢出来。
         */
        padding-top:100px;
        padding-bottom:100px;
        box-sizing: border-box;
      }

      .box3{
        position: fixed;
        bottom:0px;
        left:0px;
        width: 100%;
        height: 100px;
        background-color: green;
      }

  </style>
  <div class="box">
      <div class="box1"></div>
      <div class="box2"></div>
      <div class="box3"></div>
  </div>
 
</body>
</html>

相关文章

网友评论

      本文标题:02-布局中margin和padding区别

      本文链接:https://www.haomeiwen.com/subject/lmsxyftx.html