html+css实现三列布局的4种方式

面试问到一个问题,要设计左右两边固定100px,中间自动填充,总长度为100%的一个页面

刚开始我说用栅格,实践上确实不行,所以去百度下如何实现,自己去实现了4种方式分别是:BFC块级布局,flex布局,table布局,css计算宽度布局

由于不懂BFC布局,所以在实现布局的时候走了很多弯路,一直复现失败,但后调整了html中的div顺序解决了问题,直到现在我还是不能理解这个问题,等我看懂了再过来更新吧

直接上代码:

BFS实现:

<div class= "container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="middle"></div>
</div>

<style>
/*方法一: BFC(块级格式化上下文)*/
    .container{
        width:100%;height:400px;border: 1px  red;
    }
    .left{
        width:100px;height:100%;
        background: gray;
        float: left;
    }
    .right{
        width:100px;
        height:100%; 
        float: right; /* bfc模块触发 */
        background: green;
    }
    .middle{
        width: auto;
        height: 100%;
        overflow:hidden;  /* bfc模块触发,如过取消将出现文字环绕效果 */
        background: red;
    }

</style>

Flex实现:

<div class= "container">
    <div class="left"></div>
    <div class="middle"></div>
    <div class="right"></div>
</div>
<style>
     .container{
        width:100%;height:400px;border:1px solid red;
        display:flex;        
    }
    .left{
        width:100px; height:100%;background:gray;
        flex:none;
    }
    .middle{
        width: auto;
        height: 100%;
        background: red;
        flex:1;
    }
    .right{
        height:100%;
        width: 100px;
        background:green;
        flex:none;        
    }
    
</style>

Flex学习:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html

Table布局格式:

<div class= "container">
    <div class="left"></div>
    <div class="middle"></div>
    <div class="right"></div>
</div>
<style>
     .container{
        width:100%;height:400px;border:1px solid red;
        display:table;         
    }
    .left{
        width:100px; height:100%;background:gray;
        display:table-cell;
    }
    
    .middle{
        width: auto;
        height: 100%;
        background: red;
        display: table-cell;
    }
    .right{
        width: 100px;
        height:100%;
        background:green;
        display: table-cell;
    }
</style>

css样式计算:

<div class= "container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="middle"></div>
    
</div>
<style>
    .container{
        width:100%;height:400px;border:1px solid red;
    }
    .left{
        width:100px;height:100%;background:gray;
        float:left;
    }
    .middle{
        width:calc(100% - 100px);
        height: 100%;
        background: red;
    } 
    .right{
        height:400px;background:green;
        float:right;
        width:100px;
    }
</style>

总结:不去参加面试不知道自己到底有多垃圾,积少成多吧,等下次机会到来的时候别再错过就行了

猜你喜欢

转载自blog.csdn.net/u013455430/article/details/86477416