题目:假设高度已知,请写出三栏布局,其中左栏、右栏宽度各为300px,中间自适应。
一、浮动解决方案
<style>
.wrap div {
height: 100px;
}
.left {
float: left;
width: 300px;
background-color: red;
}
.right {
float: right;
width: 300px;
background-color: blue;
}
.center {
background-color: yellow;
}
</style>
<body>
<div class="wrap">
// 注意此处div是左右中的写法
<div class="left">1</div>
<div class="right">3</div>
<div class="center">2</div>
</div>
</body>
【评价】:
优点:兼容性较好
缺点:使用浮动以后,元素脱离文档流,如果处理不好会带来很多问题,这是该方法本身的局限性。
二、绝对定位解决方案
<style>
.wrap div {
height: 100px;
}
.left {
width: 300px;
position: absolute;
left: 0;
background: red;
}
.right {
width: 300px;
position: absolute;
right: 0;
background: blue;
}
.center {
position: absolute;
left: 300px;
right: 300px;
background: yellow;
}
</style>
<body>
<div class="wrap">
<div class="left">1</div>
<div class="center">2</div>
<div class="right">3</div>
</div>
</body>
【评价】
优点:快捷,配合js使用不容易出问题
缺点:由于布局已经脱离文档流,意味着下面所有子元素也必须脱离文档流,导致了该方案的可使用性较差。
三、flex布局解决方案
<style>
.wrap {
display: flex;
}
.wrap div {
height: 100px;
}
.left {
width: 300px;
background: red;
}
.right {
width: 300px;
background: blue;
}
.center {
flex: 1;
background: yellow;
}
</style>
<body>
<div class="wrap">
<div class="left">1</div>
<div class="center">2</div>
<div class="right">3</div>
</div>
</body>
【评价】:flex布局是在浮动布局和绝对定位布局之后,在CSS3中新出现的一种布局方式,flex布局就是为解决前面两种方式的缺点而出现的,是一种比较完美的解决方案
四、表格布局解决方案
<style>
.wrap {
width: 100%;
display: table;
height: 100px;
}
.wrap div {
display: table-cell;
}
.left {
width: 300px;
background: red;
}
.right {
width: 300px;
background: blue;
}
.center {
background: yellow;
}
</style>
<body>
<div class="wrap">
<div class="left">1</div>
<div class="center">2</div>
<div class="right">3</div>
</div>
</body>
五、网格布局解决方案
<style>
.wrap {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.left {
background: red;
}
.right {
background: blue;
}
.center {
background: yellow;
}
</style>
<body>
<div class="wrap">
<div class="left">1</div>
<div class="center">2</div>
<div class="right">3</div>
</div>
</body>
页面布局的变通
三栏布局
- 左右宽度固定,中间自适应
- 上下宽度固定,中间自适应
两栏布局 - 左宽度固定,右自适应
- 右宽度固定,左自适应
- 上宽度固定,下自适应
- 下宽度固定,上自适应