自适应布局是在网页开发中很常见的一种布局方式,就是为了适配不同屏幕尺寸的设备,页面元素中内容主体的宽度或高度会根据浏览器窗口的大小自动调整。以下是几种自适应布局的实现:
自适应布局一:左侧宽度固定,右侧宽度自适应
HTML:
<div class="box">
<div class="left"></div>
<div class="right"></div>
</div>
CSS:
.left {
width: 200px;
float: left;
}
.right {
margin-left: 200px;
}
或
.left {
width: 200px;
position: absolute;
top: 0;
left: 0;
}
.right {
margin-left: 210px;
}
自适应布局二:右侧宽度固定,左侧宽度自适应
HMTL:
<div class="box">
<div class="right"></div> // ! 要将右侧部分的 html 结构提前书写
<div class="left"></div>
</div>
CSS:
.left {
margin-right: 210px;
}
.right {
width: 200px;
float: right;
}
或
HTML:
<div class="box">
<div class="left"></div>
<div class="right"></div>
</div>
CSS:
.left {
height: 100px;
margin-right: 210px;
background-color: #f00;
}
.right {
width: 200px;
height: 100px;
position: absolute;
top: 0;
right: 0;
background-color: #ff0;
}
自适应布局二:左侧、右侧宽度固定,中间宽度自适应
HTML:
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
CSS:
.left {
width: 200px;
height: 100px;
float: left;
background-color: #f00;
}
.center {
height: 100px;
margin-left: 210px;
margin-right: 210px;
background-color: #0f0;
}
.right {
width: 200px;
height: 100px;
float: right;
background-color: #ff0;
}
或
.left {
width: 200px;
height: 100px;
position: absolute;
top: 0;
left: 0;
background-color: #f00;
}
.center {
height: 100px;
margin-left: 210px;
margin-right: 210px;
background-color: #0f0;
}
.right {
width: 200px;
height: 100px;
position: absolute;
top: 0;
right: 0;
background-color: #ff0;
}
自适应布局三:上、下高度固定,中间高度自适应
HTML:
<body>
<div class="top"></div>
<div class="middle"></div>
<div class="bottom"></div>
</body>
CSS:
html, body {
height: 100%;
overflow: hidden;
}
.top {
width: 100%;
height: 80px;
background-color: #000;
position: absolute;
top: 0;
left: 0;
}
.middle {
width: 100%;
overflow: auto;
position: absolute;
left: 0;
right: 0;
top: 80px;
bottom: 80px;
background-color: #ff0;
}
.bottom {
width: 100%;
height: 80px;
position: absolute;
left: 0;
bottom: 0;
background-color: #f00;
}
|