经常会看到这样的布局,比如博客左栏要放导航,宽度固定,右边显示内容,然后右栏的内容要根据窗口的缩放自适应。
第一种方法比较简单,也是大多数人比较常用的。
一、使用margin实现左固定右自适应
1.html代码
1
2
|
<
div
id
=
"left"
></
div
>
<
div
id
=
"right"
></
div
>
|
2.css代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
html, body {
margin
:
0
;
padding
:
0
;
}
#
left
{
width
:
100px
;
height
:
100px
;
background
:
red
;
float
:
left
;
}
#
right
{
height
:
200px
;
background
: yellow;
margin-left
:
110px
;
}
|
3.实例演示
二、使用position:absolute实现的左固定右自适应
有的人可能会想说绝对定位也可以实现,暂时不考虑更复杂的情况,也可以算一种实现的方法。html结构不变
1.css代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
html, body {
margin
:
0
;
padding
:
0
;
}
#
left
{
width
:
100px
;
height
:
100px
;
background
:
red
;
position
:
absolute
;
}
#
right
{
height
:
200px
;
background
: yellow;
margin-left
:
110px
;
}
|
2.实例演示
使用position:absolute实现的左固定右自适应
还有其他的方法吗?看一下w3c怎么实现的。
左边的区域使用左浮动和定义宽度
右边的区域使用overflow:hidden,触发了Block Formatting Context,这样右边就会填满整个区域。
把这个方法用到我们的例子,html结构不变
三、使用overflow:hidden实现的左固定右自适应
1.css代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
html, body {
margin
:
0
;
padding
:
0
;
}
#
left
{
float
:
left
;
width
:
100px
;
height
:
100px
;
background
:
red
;
margin-right
:
10px
;
}
#
right
{
height
:
200px
;
background
: yellow;
overflow
:
hidden
;
}
|
2.实例演示
使用overflow:hidden实现的左固定右自适应
哪种方法比较好,我想每个人心中都有底了。