共计 1716 个字符,预计需要花费 5 分钟才能阅读完成。
经典 CSS 题目:三栏布局
假设页面高度已知,请写出三栏布局,其中左栏、右栏宽度各为 300px,中间自适应。
- 方法 1:浮动解决方案
<style>
.layout{
width: 100%;
min-height: 200px;
}
.layout .left{
float:
left;width: 300px;
background: red;
}
.layout .right{
float: right;
width: 300px;background: blue;
}
.layout .center{background: yellow;}
</style>
<section class="layout float">
<div class="left"> 左 </div>
<div class="right"> 右 </div>
<div class="center"> 中 </div>
</section>
- 方法 2: 定位
<style>
.layout{
width: 100%;
min-height: 200px;
}
.layout .left{
position: absolute;
left: 0;
width: 300px;
background: red;
}
.layout .right{
position: absolute;
right: 0;
width: 300px;
background: blue;
}
.layout .center{
left: 300px;
right: 300px;
background: yellow;
}
</style>
<section class="layout absolute">
<div class="left"> 左 </div>
<div class="right"> 右 </div>
<div class="center"> 中 </div>
</section>
- 方法 3:flexbox
<style>
.layout{
width: 100%;
display: flex;
min-height: 200px;
}
.layout .left{
width: 300px;
background: red;
}
.layout .right{
width: 300px;
background: blue;
}
.layout .center{
flex: 1;
background: yellow;
}
</style>
<section class="layout flexbox">
<div class="left"> 左 </div>
<div class="center"> 中 </div>
<div class="right"> 右 </div>
</section>
- 方法 4:表格
<style>
.layout{
width: 100%;
display: table;
min-height: 200px;
}
.layout>div{display: table-cell;}
.layout .left{
width: 300px;
background: red;
}
.layout .right{
width: 300px;
background: blue;
}
.layout .center{
flex: 1;
background: yellow;
}
</style>
<section class="layout table">
<div class="left"> 左 </div>
<div class="center"> 中 </div>
<div class="right"> 右 </div>
</section>
- 方法 5:网格布局
<style>
.layout{
width: 100%;
display: grid;
grid-template-columns: 300px auto 300px;
grid-template-rows: 100px;
}
.layout .left{background: red;}
.layout .right{background: blue;}
.layout .center{background: yellow;}
</style>
<section class="layout grid">
<div class="left"> 左 </div>
<div class="center"> 中 </div>
<div class="right"> 右 </div>
</section>
正文完