1.前言
css布局是前端面试最常见的问题,这里仅就其中最常见的4种展示代码及效果
2.搞起
2.1 单栏布局
- 如名字,全部块级元素按照一个顺序单列显示在页面中
- 即 header, main,footer 统一被包裹在content中,单列显示在html页面中:
|HTML文件|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="layout">
<div id="content" class="header">header</div>
<div id="content" class="main">main</div>
<div id="content" class="foot">foot</div>
</div>
</body>
</html>
|CSS文件|
#content{
margin: 0 auto;
margin-bottom:20px;
}
.header{
height:50px;
background:red;
}
.main{
height:500px;
background:blue;
}
.foot{
height:100px;
background:yellow;
}
效果:详见链接
2.2 三列布局
- 两侧两列固定宽度,中间列自适应宽度
我加入了边框顺便通过overflow解决了浮动问题
|html|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="wrap" id="float3" style="overflow:hidden; *zoom:1;border:20px solid">
<div id="layout" class="left">我是left</div>
<div id="layout" class="right">我是right</div>
<div id="layout" class="main">我是main</div>
</div>
</body>
</html>
|CSS配置|
#layout{
height:400px;
}
.left{
width:100px;
float:left;
background:green;
}
.right{
width:200px;
float:right;
background:yellow;
}
.main{
margin-left: 100px;
margin-right: 200px;
background:pink;
}
效果:详见链接
2.3 圣杯布局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
#content:after{
content: '';
display: block;
clear: both;
}
#content{
padding-left: 100px;
padding-right: 150px;
}
.aside, .main, .extra{
float: left;
}
.aside{
width: 100px;
height: 300px;
background: red;
margin-left: -100%;
position: relative;
left: -100px;
}
.extra{
width: 150px;
height: 300px;
background: yellow;
margin-left: -150px;
position: relative;
left: 150px;
}
.main{
height: 350px;
background: blue;
width: 100%;
}
</style>
</head>
<body>
<div id="content">
<div class="main">main</div>
<div class="aside">aside</div>
<div class="extra">extra</div>
</div>
</body>
</html>
2.4 双飞翼布局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
#content:after{
content: '';
display: block;
clear: both;
}
#content{
}
.aside, .main, .extra{
float: left;
}
.aside{
width: 100px;
height: 300px;
background: red;
margin-left: -100%;
}
.extra{
width: 150px;
height: 300px;
background: yellow;
margin-left: -150px;
}
.main{
width: 100%;
}
.wrap{
margin-left: 100px;
margin-right: 150px;
background: blue;
height: 350px;
}
</style>
</head>
<body>
<div id="content">
<div class="main">
<div class="wrap">main</div>
</div>
<div class="aside">aside</div>
<div class="extra">extra</div>
</div>
</body>
</html>