1、前言
在我们整个PC端的项目上,有很多的主页面布局采用的是两列布局,左侧定,右侧自适应;或者右侧定,左侧自适应
2、上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body {
color: #fff;
}
.fixed-width {
margin-bottom: 10px;
color: #000;
}
.split {
height: 10px;
}
/* float + margin */
.f-content {
height: 200px;
}
.f-left {
float: left;
width: 200px;
height: 100%;
background: red;
}
.f-right {
margin-left: 200px;
/*width: 100%;*/
height: 100%;
background: blue;
}
/* position */
.p-content {
height: 200px;
position: relative;
padding-left: 200px;
}
.p-left {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 100%;
background: red;
}
.p-right {
/* width: 100%; */
height: 100%;
background: blue;
}
/* table布局 */
.t-content {
display: table;
width: 100%;
height: 200px;
}
.t-left {
display: table-cell;
width: 200px;
background: red;
}
.t-right {
display: table-cell;
background: blue;
}
/* flex */
.x-content {
display: flex;
height: 200px;
}
.x-left {
width: 200px;
background: red;
}
.x-right {
flex: 1;
background: blue;
}
</style>
</head>
<body>
<!-- setting -->
<div class="fixed-width">
<span>左边宽度:</span> <input type="text" id="fixed-left-width" name="name" value="" οnchange="fixedLeftChange()">
</div>
<!-- float + margin -->
<div class="f-content">
<div class="f-left" id="f-left">f-left</div>
<div class="f-right" id="f-right">f-right</div>
</div>
<div class="split"></div>
<!-- position -->
<div class="p-content" id="p-content">
<div class="p-left" id="p-left">p-left</div>
<div class="p-right">p-right</div>
</div>
<div class="split"></div>
<!-- table布局 -->
<div class="t-content">
<div class="t-left" id="t-left">t-left</div>
<div class="t-right">t-right</div>
</div>
<div class="split"></div>
<!-- flex -->
<div class="x-content">
<div class="x-left" id="x-left">x-left</div>
<div class="x-right">x-right</div>
</div>
<script type="text/javascript">
function fixedLeftChange() {
const $fixed = document.getElementById('fixed-left-width')
const leftWidth = $fixed.value
// float
document.getElementById('f-left').style.width = leftWidth + 'px'
document.getElementById('f-right').style.marginLeft = leftWidth + 'px'
// position
document.getElementById('p-content').style.paddingLeft = leftWidth + 'px'
document.getElementById('p-left').style.width = leftWidth + 'px'
// table
document.getElementById('t-left').style.width = leftWidth + 'px'
// flex
document.getElementById('x-left').style.width = leftWidth + 'px'
}
</script>
</body>
</html>
3、四套布局
- margin+float布局
- display:flex布局
- display:table & dispaly:table-cell布局
- relative+absolute布局
大家好好参考哟,很有用的
4、进阶
那么很多人问,如果我们需要高度自适应怎么处理,安排
- margin+float布局:
这个和下面三个不一样,除了去掉父级高度除外,还需要设overflow:hidden;还需要给左右两侧加这个类
.row {
margin-bottom: -10000px;
padding-bottom: 10000px;
/内外补丁是关键,父级给hidden掉了/
}
可以动手试试,很妙
- display:flex布局:
代码不动,把父级的高度去掉即可支持
- display:table & dispaly:table-cell布局
代码不动,把父级的高度去掉即可支持
- relative+absolute布局
代码不动,把父级的高度去掉即可支持