两栏式布局(侧边栏固定宽度,主体内容部分自适应)
法1:
(侧边栏左/右浮动,主体部分margin-left/margin-right为侧边栏宽度)
<style type="text/css">
.pra{
height: 500px;
}
.aside{
width:300px;
text-align: center;
line-height: 500px;
height: 100%;
background-color: bisque;
float: left;
}
.main{
text-align: center;
line-height: 500px;
margin-left: 300px;
height:100%;
background-color: #ffcccc;
}
</style>
<body>
<div class="pra">
<div class="aside">aside</div>
<div class="main">main</div>
</div>
</body>
法2
(侧边栏左/右浮动,主体部分overflow:hidden(加了BFC))
<style type="text/css">
.pra{
height: 500px;
}
.aside{
width:300px;
text-align: center;
line-height: 500px;
height: 100%;
background-color: bisque;
float: left;
}
.main{
text-align: center;
line-height: 500px;
height:100%;
background-color: #ffcccc;
overflow: hidden;
}
</style>
<body>
<div class="pra">
<div class="aside">aside</div>
<div class="main">main</div>
</div>
</body>
tips:主体部分不做处理,虽然看起来有了自适应,但其实主体部分是整个pra,侧边栏浮动之后在上面,覆盖了主体的内容。
三栏式布局(两边侧边栏固定宽度,中间主体部分自适应)
法1:
(绝对定位法:左右绝对定位,主体用margin隔开)
<style type="text/css">
body{
margin:0;
padding:0;
}
.pra{
position: relative;
height:300px;
}
.left,.right{
width:200px;
height:100%;
position: absolute;
top:0;
/* 没加top的时候右块是在下面的*/
}
.left{
left:0;
background-color: #ffcccc;
}
.right{
right:0;
background-color: bisque;
}
.main{
margin:0 210px;/*210是因为两边有距离,不需要可不加*/
background-color: mediumpurple;
height:100%;
}
</style>
<body>
<div class="pra">
<div class="left"></div>
<div class="main"></div>
<div class="right"></div>
</div>
</body>
缺点:当主体部分有内容时,缩小到不够原来的布局时内容会重叠。
法2:
(负margin法:主体部分下内容放在再一个子元素里,给这个子元素加margin,且left,right,main均左浮动)
<style type="text/css">
.pra{
height:300px;
}
.main,.left,.right{
float: left;
height:100%;
}
.left,.right{
width:200px;
}
.main{
width:100%;
}
.left{
background-color: #ffcccc;
margin-left:-100%;
}
.right{
margin-left:-200px;
background-color: bisque;
}
.main .body{
margin:0 210px;
background-color: mediumpurple;
height:100%;
}
</style>
<body>
<div class="pra">
<div class="main">
<div class="body"></div>
</div>
<div class="left"></div>
<div class="right"></div>
</div>
帮助理解:
在没有left和right没有加负margin的时候是这样的:
全部浮动之后,left和right其实是跟在main后面的,加上margin就到了所要去的位置
法3
(自身浮动:left左浮动,right右浮动,main加margin。main的位置一定要在left和right之后,其他两个无所谓。)
<style type="text/css">
.pra{
height:300px;
}
.left,.right{
width:200px;
height:100%;
}
.left{
float: left;
background-color: #ffcccc;
}
.right{
float: right;
background-color: bisque;
}
.main{
background-color: mediumpurple;
margin:0 210px;
height:100%;
}
</style>
<body>
<div class="pra">
<div class="left"></div>
<div class="right"></div>
<div class="main"></div>
</div>
</body>
tips:注意的地方是main一定要放在left和right之后,不然会导致结构混乱:
<body>
<div class="pra">
<div class="left"></div>
<div class="main"></div>
<div class="right"></div>
</div>
</body>
right是被main挤下来的,用Chrome检查main发现: