首先给出基本的HTML结构
<div id="wrap">
<div id="sidebar" style="height:240px;">固定宽度区</div>
<div id="content" style="height:340px;">自适应区</div>
</div>
<div id="footer">后面的一个DIV,以确保前面的定位不会导致后面的变形</div>
方法一
固定宽度区浮动,自适应区不设宽度而设置 margin
#wrap {
overflow: hidden; *zoom: 1;
}
#content ,#sidebar {
background-color: #eee;
}
#sidebar {
float: right; width: 300px;
}
#content {
margin-right: 310px;
}
#footer {background-color: #f00;color:#fff; margin-top: 1em}
原理:div有个默认属性,即如果不设置宽度,那他会自动填满他的父标签的宽度。即宽度为100%,而宽度100%是相对于他的父标签来的,如果我们改变了他父标签的宽度,那content的宽度也就会变——比如我们把浏览器窗口缩小,那wrap的宽度就会变小,而content的宽度也就变小——但,他的实际宽度100%-310始终是不会变的。
只要我们记得清除浮动(这里我用了最简单的方法),那footer也不会错位。而且无论content和sidebar谁更长,都不会对布局造成影响。
限制——html中sidebar必须在content之前
要点:将侧边区块<aside>域浮动,<aside>浮动后覆盖绿色<main>, 再将<main> overflow:auto,形成BFC,形成独立区域,达到效果。
方法二
固定宽度区使用绝对定位,自适应区照例设置margin
#wrap {
*zoom: 1; position: relative;background-color: #eee;
}
#sidebar {
width: 300px; position: absolute; right: 0; top: 0;background-color: #eee;
}
#content {
margin-right: 310px;
}
这段css中要注意给wrap加上了相对定位,以免sidebar太绝对了跑到整个网页的右上角而不是wrap的右上角。
不足:因为wrap对sidebar的无视,由于绝对定位会让其他元素无视他的存在,会造成footer跑到上面去。这种定位方式只能满足sidebar自己,但对他的兄弟们却毫无益处
方法三
float与margin齐上阵
把content的宽度设为100%,然后设置float:left,最后把他向左移动310,以便于sidebar能挤上来。
但这么一来content里面的内容也会跟着左移310,导致被遮住了,所以我们要把他重新挤出来。为了好挤,我用了一个额外的div包裹住内容,所以html结构变成了这种样子。
<div id="wrap">
<div id="content" style="height:140px;">
<div id="contentb">
content自适应区,在前面
</div>
</div>
<div id="sidebar" style="height:240px;">sidebar固定宽度区</div>
</div>
#sidebar {
width: 300px; float: right;background-color: #eee;
}
#content {
margin-left: -310px; float: left; width: 100%;background-color: #eee;
}
#contentb {
margin-left: 310px;
}
方法四
使用负边距
<div id="main">
<div class="center">
<div class="content">
main main main main main main
</div>
</div>
<div class="aside"></div>
</div>
<div class="footer"></div>
#header,#footer{
height: 100px;
background-color: red;
/* overflow: hidden; */
}
#main{
overflow: hidden;
}
#main .center{
height: 200px;
width: 100%;
float: left;
}
.center .content{
height: 200px;
background: green;
margin-right: 100px;
}
#main .aside{
height: 200px;
width: 100px;
background: blue;
float: left;
margin-left: -100px;
}
1371

被折叠的 条评论
为什么被折叠?



