css之页面两列布局

时间:2024-11-30 16:04:07

两列布局:左边固定,右边自适应

第一种方法:左边的div左浮动或者是绝对定位,右边的div加margin-left:左边div的宽度

html部分

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

css部分

.left {
position: absolute; /*这可以换成float:left,都可以使其脱离文档流*/
height: 100px;
width: 300px;
background-color: blue;
}
.right {
height: 200px;
margin-left: 300px;
background-color: red;
}

第二种方法:BFC(块级格式化上下文)

对于BFC的理解可以看 http://www.cnblogs.com/vitruvi/p/4303891.html

html部分和上面是一样的,下面只写css部分

.left {
float: left;
height: 200px;
width: 300px;
background-color: blue;
}
.right {
overflow: auto;
height: 200px;
      background-color:red;
}

 第三种方法:这种方法其实是第一种方法的延伸

<div style="float:left;width:100%">
<p style="margin-right:170px;">文字</p>
</div>
<img width='' style='float:left;margin-left:-150px;'>

这种方法与第一种方法的比较的好处就是dom的顺序和显示的顺序是一致的

第四种方法:flex

css:

 .containter{
display: flex;
}
.left {
width: 200px;
background-color: blue;
}
.right {
background-color: red;
flex:1;
}

html:

<div class="containter">
<div class="left">left</div>
<div class="right">right</div>
</div>

第五种方法:table

       html *{
margin:0;
padding: 0;
}
.containter{
display: table;
width: 100%;
height: 100%;

}
.left {
width: 200px;
background-color: blue;
display: table-cell;
}
.right {
background-color: red;
display: table-cell;
}
<body>
<div class="containter">
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>

第六种:grid

.containter{
display: grid;
width: 100%;
height: 100%;
grid-template-rows:100px;
grid-template-columns:200px auto;
}
.left {
width: 200px;
background-color: blue;
}
.right {
background-color: red;
}

两列布局:右边固定,左边自适应

第一种:float或position,其实和上面差不多

    .containter{
width:400px;
height: auto;
}
.right{
width:100px;
background: red;
float: right;
}
.left{
margin-right: 100px;
background: blue;
}

html

<div class="containter">
<div class="right">right</div>
<div class="left">left</div>
</div>

第二种方法:BFC

  .left {
height: 200px;
overflow: auto;
background-color: blue;
}
.right {
float: right;
background-color: red;
height: 200px;
width: 300px;
}

html同上