横向两列布局(左列固定,右列自适应)的4种CSS实现方式

转载:https://www.jb51.net/css/455079.html

需要实现横向两列布局:左列固定,右列自适应的效果,如下图:

1.html

<DOCTYPE html>  
<html>  
<head>  
<meta charset="UTF-8">  
<title>测试练习</title>  
</head>  
<body>  
<div class="parent">    
    <div class="side">侧栏</div>  
    <div class="main">主栏</div>  
</div>  
</body>  
</html>  

2.方法一(推荐):使用asolute属性实现,需要注意:固定宽的列的高度>自适应宽度列的高度

CSS代码:

body{   
    margin:0;   
    padding:0;   
    font-size:30px;   
    font-weight:bold;       
}   
.parent{   
    text-align:center;   
    line-height:200px;   
}       
.side{   
    position:absolute;left:0;top:0;   
    width:200px;   
    height:200px;   
    background:red;   
}   
.main{   
    margin-left:210px;   
    background:blue;   
    height:200px;   
}

3.方法二:通过设置float属性(使纵向排列的块级元素,横向排列)及margin属性(设置两列之间的宽度)

CSS代码:

body{   
    margin:0;   
    padding:0;   
    font-size:30px;   
    font-weight:bold;       
}   
.parent{   
    text-align:center;   
    line-height:200px;   
}   
.side{   
    width:200px;   
    height:200px;   
    float:left;   
    background:red;   
}   
.main{   
    height:200px;   
    margin-left:210px;   
    background:blue;   
} 

4.方法三:使用Flex布局

CSS代码:

body{   
        margin:0;   
        padding:0;   
        font-size:30px;   
        font-weight:bold;       
    }   
    .parent{   
        text-align:center;   
        line-height:200px;   
        display:flex;   
    }    
    .side{   
        width:200px;   
        height:200px;   
        background:red;   
        margin-right:10px;   
    }   
    .main{   
        background:blue;   
        height:200px;   
        flex:1;   
    }​ 

5.方法四:利用BFC不与浮动元素重叠的特性

CSS代码:

 body{   
    margin:0;   
    padding:0;   
    font-size:30px;   
    font-weight:bold;       
}   
.parent{   
    text-align:center;   
    line-height:200px;   
}   
.side {   
  width: 200px;   
  height: 100px;   
  float: left;   
  background: red;   
  margin-right: 10px;   
}   
.main {   
  /* 创建BFC   */  
  overflow: hidden;   
  background: blue;   
  height: 100px;   
} 

猜你喜欢

转载自blog.csdn.net/hangGe0111/article/details/84863285
今日推荐