CSS:float理解。用两种不同的方式来实现一个三列布局,其中左侧和右侧的部分宽度固定,中间部分宽度随浏览器宽度的变化而自适应变化

用两种不同的方式来实现一个三列布局,其中左侧和右侧的部分宽度固定,中间部分宽度随浏览器宽度的变化而自适应变化。

方法一:浮动+margin

HTML:

<div class="sectionLeft">左</div>

<div class="sectionRight">右</div>

<div class="sectionMid">中</div>

注意:先写左边的div,再写右边的div,最后写中间的。

CSS:

.sectionLeft{
    float: left;
    width:200px;
    height: 400px;
    background-color: red;
}
.sectionMid{
    margin: 0px 210px;
    height: 400px;
    background-color: green;
}
.sectionRight{
    float: right;
    width: 200px;
    height: 400px;
    background-color: blue;
}

谷歌浏览器运行效果如下:

HTML中若按照左、中、右的正常顺序来写,则右边部分会下去。运行效果如下:

网上大佬的解释如下:

假如某个div元素A是浮动的,如果A元素上一个元素也是浮动的,那么A元素会跟随在上一个元素的后边(如果一行放不下这两个元素,那么A元素会被挤到下一行);如果A元素上一个元素是标准流中的元素,那么A的相对垂直位置不会改变,也就是说A的顶部总是和上一个元素的底部对齐。(原文参见:http://www.cnblogs.com/iyangyuan/archive/2013/03/27/2983813.html

方法二:父盒子相对定位,子盒子绝对定位

HTML:

<div class="box">

    <div class="box1">左</div>

    <div class="box2">中</div>

    <div class="box3">右</div>

</div>

CSS:

.box{
    position: relative;
    margin: 0 auto;
}
.box1{
    position: absolute;
    top:0px;
    left:0px;
    background-color: red;
    width:200px;
    height:200px;
}
.box2{
    background-color: green;
    width: auto;
    height:200px;
}
.box3{
    position: absolute;
    top:0px;
    right:0px;
    background-color: blue;
    width:200px;
    height:200px;
}

运行效果同方法一。

发布了22 篇原创文章 · 获赞 7 · 访问量 4492

猜你喜欢

转载自blog.csdn.net/lucky_jiexia/article/details/86007323