css中间固定,两边自适应布局方式:float,position,flex及各自知识点

141 阅读1分钟

1、float方式

    /**样式如下**/
        <style>
         .content-box{
            height: 200px;
        }
        .l-box{
            float: left;
            width: 200px;
            height: 100%;
            background-color: pink;
        }
        .r-box{
            float: right;
            width: 200px;
            height: 100%;
            background-color: yellow;
        }
        .center{
            margin: 0 200px;
            height: 100%;
            background-color: green;
        }
     </style>
    /**结构如下**/
     <div class="content-box">
        <div class="l-box"></div>
        <div class="r-box"></div>
        <div class="center"></div>
    </div>
浮动可以理解为让某个div元素脱离标准流,漂浮在标准流之上,和标准流不是一个层次。
浮动产生的原因:父元素不加高度,子元素加浮动后撑不开父元素。
清除浮动的几种方式:
1.给父元素加高度。
2.给父元素加overflow:hidden,把父元素弄成BFC。
3.在父元素最后一行加空元素设置clear:both。
4.利用伪元素:after,加clear:both
.clearfix:after{
    content: '';
    display:block;
    height:0;
    clear:both;
    visiblity:hidden;
}
.clearfix{
    *zoom:1;//ie 6,7
}
双伪元素
.clearfix:before,.clearfix:after{
    content: '';
    display: table;
}
.clearfix:after{
    clear:both;
}
.clearfix{
    *zoom:1;//ie 6,7
}

2、position方式

/**样式如下**/
 <style>
      .content-box{
            height: 200px;
            position: relative;
        }
        .l-box{
            position: absolute;
            left: 0;
            top: 0;
            width: 200px;
            height: 100%;
            background-color: yellow;
        }
        .r-box{
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 100%;
            background-color: pink;
        }
        .center {
            margin: 0 200px;
            height: 100%;
            background-color: gray;
        }
 </style>
 /**结构如下**/
  <div class="content-box">
        <div class="l-box"></div>
        <div class="center"></div>
        <div class="r-box"></div>
    </div>

3、flex方式

/**样式如下*/
<style>
        .content-box{
            height: 200px;
            display: flex;
        }
        .l-box{
            width: 200px;
            height: 100%;
            background-color: yellow;
        }
        .center{
            flex:1;
            background-color: turquoise;
        }
        .r-box{
            width: 200px;
            height: 100%;
            background-color: pink;
        } 
  </style>
  /**结构如下**/
   <div class="content-box">
        <div class="l-box"></div>
        <div class="center"></div>
        <div class="r-box"></div>
    </div>