1. 两栏布局的实现
一般两栏布局指的是左边一栏宽度固定,右边一栏宽度自适应,两栏布局的具体实现:
- 利用浮动,将左边元素宽度设置为200px,并且设置向左浮动。将右边元素的margin-left设置为200px,宽度设置为auto(默认为auto,撑满整个父元素)。
<style>
.container {
height: 100px;
}
.left {
float: left;
width: 200px;
background: red;
height: 100px;
}
.right {
margin-left: 200px;
width: auto;
background: green;
height: 100px;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
- 利用浮动,左侧元素设置固定大小,并左浮动,右侧元素设置overflow: hidden; 这样右边就触发了BFC,BFC的区域不会与浮动元素发生重叠,所以两侧就不会发生重叠。
<style>
.container {
height: 100px;
}
.left {
float: left;
width: 200px;
background: red;
height: 100px;
}
.right {
overflow:hidden;
background: green;
height: 100px;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
- 利用绝对定位,将父级元素设置为相对定位。左边元素设置为absolute定位,并且宽度设置为200px。将右边元素的margin-left的值设置为200px。
<style>
.container {
position:relative;
height: 100px;
}
.left {
position:absolute;
width: 200px;
background: red;
height: 100px;
}
.right {
margin-left:200px;
background: green;
height: 100px;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
- 利用flex布局,将左边元素设置为固定宽度200px,将右边的元素设置为flex:1。
<style>
.container {
display:flex;
height: 100px;
}
.left {
width: 200px;
background: red;
height: 100px;
}
.right {
flex:1;
background: green;
height: 100px;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
2. 三栏布局实现
三栏布局一般指的是页面中一共有三栏,左右两栏宽度固定,中间自适应的布局,三栏布局的具体实现:
- 利用绝对定位,左右两栏设置为绝对定位,中间设置对应方向大小的margin的值。
<style>
.container{
position: relative;
height:100px;
}
.left{
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background-color: red;
}
.right{
position: absolute;
right: 0;
top: 0;
width: 200px;
height: 100px;
background-color: orange;
}
.center{
margin-left: 100px;
margin-right: 200px;
height: 100px;
background-color: blue;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
- 利用浮动,左右两栏设置固定大小,并设置对应方向的浮动。中间一栏设置左右两个方向的margin值,注意这种方式,中间一栏必须放到最后
<style>
.container{
height:100px;
}
.left{
float:left;
width: 100px;
height: 100px;
background-color: red;
}
.right{
float:right;
width: 200px;
height: 100px;
background-color: orange;
}
.center{
margin-left: 100px;
margin-right: 200px;
height: 100px;
background-color: blue;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
</body>
- 利用flex布局,左右两栏设置固定大小,中间一栏设置为flex:1。
<style>
.container{
display:flex;
height:100px;
}
.left{
width: 100px;
height: 100px;
background-color: red;
}
.right{
width: 200px;
height: 100px;
background-color: orange;
}
.center{
flex:1;
height: 100px;
background-color: blue;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
文档更新时间: 2023-01-05 17:22 作者:孙老师