在面试的时候,面试官经常问的就是css的布局方式,我总结了以下五种方式:
- 浮动布局
- 定位布局
- 表格(table)布局
- 弹性(flex)布局
- 网格(grid)布局
下面就用最经典的面试题来进行讲解:
三栏并排布局,左侧一栏高度100px,宽度300px,右侧一栏高度100px,宽度100px,中间一栏宽度自适应 ,高度为100px
- 浮动布局:使用float来进行布局
<style>
.left {
width: 100px;
height: 100px;
float: left;
background-color: red;
}
.center {
height: 100px;
background-color: blue
}
.right {
width: 100px;
height: 100px;
float: right;
background-color: orange;
}
</style>
<body>
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</body>
- 定位布局
<style>
.left {
position: absolute;
top: 0;
left: 0;
width: 100px;
background-color: red;
}
.center {
position: absolute;
top: 0;
left: 100px;
right: 100px;
background-color: blue;
}
.right {
position: absolute;
top: 0;
right: 0;
width: 100px;
background-color: orange;
}
div {
height: 100px;
}
</style>
<body>
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</body>
注:中间div的定位设置,必须left的值跟right的值相等,这样才能实现自适应。
- 表格布局
<style>
.table {
display: table;
width: 100%;
}
.left {
width: 100px;
background-color: red;
}
.center {
background-color: blue;
}
.right {
width: 100px;
background-color: orange;
}
.table>div {
height: 100px;
display: table-cell;
}
</style>
<body>
<div class="table">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
- 弹性布局
<style>
.flex {
display: flex;
flex-direction: row;
}
.left {
width: 100px;
background-color: red;
}
.center {
flex: 1;
background-color: blue;
}
.right {
width: 100px;
background-color: orange;
}
.flex>div {
height: 100px;
}
</style>
<body>
<div class="flex">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
- 网格布局
<style>
.grid {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 100px auto 100px;
}
.left {
background-color: red;
}
.center {
background-color: blue;
}
.right {
background-color: orange;
}
</style>
<body>
<div class="grid">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
以上内容,仅供自己学习,如发现错误,请留言指出。