两栏布局的五种简单实现

58 阅读1分钟

两栏布局(左边一栏宽度固定,右边一栏宽度自适应)

左边元素固定,右边元素浮动(margin-left设置为左边的宽度)

<body>
    <!-- 两栏布局 -->
    <div class="father">
        <div class="son1"></div>
        <div class="son2"></div>
    </div> </body> <style>
    .father{
        width: 400px;         
        height: 400px;
        background: burlywood;
    } 
    .son1{
        width: 100px;
        height: 100px;
        background: palegreen;
        float: left;
    }
    .son2{
        height: 100px;
        background: cornflowerblue;
        margin-left: 100px;
    } 
</style>

左边元素固定宽度并设置左浮动,右侧元素设置overflow:hidden(右边元素触发BFC,BFC的区域不会与浮动元素发生重叠)

<body>
<!-- 两栏布局 -->
<div class="father">
    <div class="son1"></div>
    <div class="son2"></div>
</div> 
</body> 
<style>
.father{
    width: 400px;
    height: 400px;
    background: burlywood;
}
.son1{
    width: 100px;
    height: 100px;
    background: palegreen;
    float: left;
}
.son2{
    height: 100px;
    background: cornflowerblue;
    overflow: hidden;
}
</style>

利用绝对定位,将父级元素设置为相对定位。左边元素设置为absolute定位,并且设置固定宽度。将右边元素的margin-left的值设置为左边的固定宽度。

<body>
    <!-- 两栏布局 -->
    <div class="father">
        <div class="son1"></div>
        <div class="son2"></div>
    </div> </body> <style>
    .father{
        width: 400px;
        height: 400px;
        background: burlywood;
        position: relative;
    }
    .son1{
        width: 100px;
        height: 100px;
        background: palegreen;
        position: absolute;
    }
    .son2{
        height: 100px;
        background: cornflowerblue;
        margin-left: 100px;
    }
</style>

 

flex布局,左边固定宽度,右边设置flex:1

<body>
    <!-- 两栏布局 -->
    <div class="father">
        <div class="son1"></div>
        <div class="son2"></div>
    </div> </body>
    <style>
    .father{
    width: 400px;
    height: 400px;
    background: burlywood;
    display: flex; 
    }
    .son1{
    width: 100px;
    height: 100px; 
    background: palegreen;
    } 
    .son2{ 
    height: 100px; 
    background: cornflowerblue;
    flex: 1;  
    } 
     </style>

利用calc,(width: calc(100% - 200px)

<body> 
    <!-- 两栏布局 -->
    <div class="father">
        <div class="son1"></div>
        <div class="son2"></div>
    </div> </body>
    <style>
    .father{
    width: 400px;
    height: 400px;
    background: burlywood;
    display: flex
    }
    .son1{
    width: 100px;
    height: 100px;
    background: palegreen;
    }
    .son2{ 
    height: 100px;
    width: calc(100% - 100px);
    background: cornflowerblue; 
    }
</style>

效果图如下:

两栏布局.png