【css面试题】三个DIV要求水平对齐,左右两个DIV宽度固定为100px,中间那个DIV充满剩余的宽度(至少2种方法)

这是我在一家公司面试时遇到的问题,当时没有答上来!!

 

所以看到的小伙伴一定要注意了!!

 

变化浏览器宽度可看到效果:

 

然后我们来看看代码:

第一种方法:(浮动)

<style type="text/css">
        .left,.right,.center{
            border:1px solid;
            height:100px;
            text-align: center;
            line-height:100px;
            font-size:50px;
        }
        .left{
            float:left;
            width:100px;
        }
        .right{
            float:right;
            width:100px;
        }
        .center{
            margin:0 100px;
        }
</style>
<div>
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

 

第二种方法:(绝对定位)

<style type="text/css">
        .container{
            position: relative;
        }
        .left,.right,.center{
            position:absolute;/*增加绝对定位*/
            top:0;
            border:1px solid;
            height:100px;
            text-align: center;
            line-height:100px;
            font-size:50px;
        }
        .left{
            left:0;
            width:100px;
        }
        .right{
            right:0;
            width:100px;
        }
        .center{
            width:auto;
            left:100px;
            right:100px;
        }
</style>
<div class="container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

 

刚发布不久,就有个小伙伴在下面评论了第三种方法

第三种方法:(fiex)

    浏览器支持

    Internet ExplorerFirefoxOperaGoogle ChromeSafari

    目前主流浏览器不支持 box-flex 属性。

    Internet Explorer 10 通过私有属性 the -ms-flex 支持.

    Firefox通过私有属性 -moz-box-flex 支持.

    Safari和Chrome通过私有属性 -webkit-box-flex 支持.

    注意: Internet Explorer 9及更早IE版本不支持弹性框.

<style type="text/css">
        .container{
            display:-moz-box; /* Firefox */
            display:-webkit-box; /* Safari and Chrome */
            display:box;
        }
        .left,.right,.center{
            border:1px solid;
            height:100px;
            text-align: center;
            line-height:100px;
            font-size:50px;
        }
        .left{
            width:100px;
        }
        .right{
            width:100px;
        }
        .center{
            -moz-box-flex:1.0; /* Firefox */
            -webkit-box-flex:1.0; /* Safari 和 Chrome */
            box-flex:1.0;
        }
</style>
<div class="container">
    <div class="left"></div>
    <div class="center"></div>
    <div class="right"></div>
</div>

 

当然还有很多方法,如果你有什么更好的方法,希望你能在下面评论出来,我们大家一起学习

posted @ 2016-08-12 17:39  大数据一级修炼师  阅读(2669)  评论(7编辑  收藏  举报