题目:如何实现高度200,左右宽度为300,中间自适应的三栏布局?
请大家在看到这个问题时,先想一想自己能用几种方式实现这个题目???
- 浮动布局。代码如下:
<style>
.parent {
width: 100%;
height: 200px;
}
.right {
float: right;
background: #00b3ee;
height: inherit;
width: 300px;
}
.left {
height: inherit;
float: left;
background: #eee789;
width: 300px;
}
.center {
height: inherit;
background: #7b007b;
}
</style>
<div class="parent">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
效果图:
这里要注意的是,不要把right和center两个容器的位置放反了。
2. 绝对定位实现。代码如下:
<style>
.parent {
position: relative;
width: 100%;
height: 200px;
}
.left {
position: absolute;
width: 200px;
background: #007bff;
height: 200px;
}
.center {
position: absolute;
background: #7b007b;
height: 200px;
left: 200px;
right: 200px;
}
.right {
right: 0;
position: absolute;
width: 200px;
background: yellow;
height: 200px;
}
</style>
<div class="parent">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
效果图:
3. flex布局。代码:
<style>
.parent > *{
height: 200px;
}
.parent {
width: 100%;
height: 200px;
display: flex;
}
.left {
background: yellow;
width: 300px;
}
.center {
background: #7b007b;
flex: 1;
}
.right {
background: #00aa88;
width: 300px;
}
</style>
<div class="parent">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
效果图:
4. 表格布局。代码:
<style>
.parent {
display: table;
width: 100%;
height: 200px;
}
.parent > *{
height: 200px;
display: table-cell;
}
.left {
background: yellow;
width: 300px;
}
.center {
background: #00aa88;
}
.right {
width: 300px;
background: #00aced;
}
</style>
<div class="parent">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
效果图:
5. 最后一种, grid网格布局,代码:
.parent {
width: 100%;
display: grid;
grid-template-rows: 200px; /*行的高度*/
grid-template-columns: 300px auto 300px; /*列的宽度*/
}
.center {
background: #2fd3dc;
}
.left {
background: #ff7f78;
}
.right {
background: #007bff;
}
</style>
<div class="parent">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
效果图: