CSS 实现一行两列平分

2017-03-19  本文已影响1240人  LYF闲闲闲闲

1. float - 浮动

 #left {
        background-color: red;
        float: left;
        width: 50%;
 }
 #right {
        background-color: greenyellow;
        float: right;
        width: 50%;
 } 
<body>
   <div id="left">aaaa</div>
   <div id="right">bbbbb</div>
</body>

2. absolute - 绝对定位

    #left {
        background-color: red;
        position: absolute;
        left: 0px;
        width: 50%;
    }
    #right {
        background-color: greenyellow;
        position: absolute;
        right: 0px;
        width: 50%;
    }
<body>
   <div id="left">aaaa</div>
   <div id="right">bbbbb</div>
</body>

3. disply:table

给父元素加上 display:table使元素像一个 <table>元素
然后给子元素加上 display:table-cell使元素像一个 <td>元素

<style>
    #divide{
        display: table;
        width: 100%;
    }
    #left {
        display: table-cell;
        background-color: red;
        width: 50%;
    }

    #right {
        display: table-cell;
        background-color: greenyellow;
        width: 50%;
    }
</style>
<body>
<div id="divide">
    <div id="left">aaaa</div>
    <div id="right">bbbbb</div>
</div>
</body>
<style>
    .main {
        display: table;
        background-color: greenyellow;
        width: 100%;
    }
    .center{
        display: table-row;
    }
    .left {
        background-color: pink;
        display: table-cell;
        height:100px;
    }
    .right {
        background-color: blue;
        display: table-cell;
    }
</style>
<body>
<div class="main">
    <div class="center">
        <div class="left">aaa</div>
        <div class="right">bbb</div>
    </div>
</div>
</body>

4. Flexbox

flex属性是flex-grow , flex-shrink , flex-basis的简写。后两个属性可选。
如果flex-grow属性都为1,则它们将等分剩余空间。
如果flex-grow属性为2,其他项目都为1,则前者占据的剩余空间将比其他项多一倍。

    #divide{
        display: flex;
    }
    #left {
        background-color: red;
        flex:1;
    }
    #right {
        background-color: greenyellow;
        flex:1;
    }
<body>
<div id="divide">
    <div id="left">aaaa</div>
    <div id="right">bbbbb</div>
</div>
</body>
上一篇 下一篇

猜你喜欢

热点阅读