position与float学习笔记

position

1
position: relative | absolute | fixed;

position:static

静态定位。是 html 元素默认的定位方式,不设定元素的定位属性时默认的 position 值就是static,遵循正常的文档流对象,对象会占用文档空间,该定位方式下 top、right、bottom、left、z-index 等属性是无效的。

position:relative

相对定位。生成相对定位的元素,相对于其正常位置进行定位。元素的位置通过 left、right、top、button 属性进行规定,可以通过 z-index 进行层次分级。

position:absolute

绝对定位。生成绝对定位元素,使元素脱离文档流,并相对于其包含块进行定位,包含块可能是文档中的另一个元素或者是初始包含块,元素原先在正常文档流中所占的空间会会被后面元素占据。
绝对定位元素的包含块为离它最近的绝对定位、相对定位或者固定定位的元素 。只要父级元素设置了position 并且值不是static,那么设定了绝句对定位的子元素即以此为包含块。如果未定义包含块,则相对于layout viewport定位。

position:fixed

固定定位。生成绝对定位元素,使元素脱离文档流,并相对于浏览器窗口进行定位。通常配合z-index一起来使用。

position:fixed 在header、footer上的应用:

1
2
3
4
5
6
7
8
9
10
11
header,
footer {
position: fixed;}
header {
top: 0;
width: x;
height: x;}
footer {
bottom: 0;
width: y;
height: y;}

为了避免出现 header与footer覆盖页面内容的情况 需要对 body 进行设置

1
2
body {
padding: x 0 y;} /*为padding-top与padding-bottom部分设置header与footer占据的高度*/

float

1
float: none | left | right;
  • none:对象不浮动。
  • left:对象浮动在左边。
  • right:对象浮动在右边。

不完全脱离文档流

浮动的元素虽然脱离了正常文档流,但是还会占用文本空间。
图片会占据文本空间使文字环绕在图片周围。

1
2
3
4
<body>
<div style="float:left"><img src="plato.jpg" width="200px"></div>
<div>...</div>
</body>

父元素高度塌陷

浮动元素会使父元素的高度塌陷,即父元素在计算高度时会忽略浮动的元素。
box1的子元素box2高度均为100px但因为浮动的原因,box1的高度并未被box2撑起来。

1
2
3
4
5
6
7
<body>
<div class="box1">
<div class="box2"></div>
<div class="box2"></div>
<div class="box2"></div>
</div>
</body>

1
2
3
4
5
6
.box2 {
margin-right: 10px;
float: left;
width: 100px;
height: 100px;
background: #b72afc;}

清除浮动

clear 属性规定元素的哪一侧不允许其他浮动元素。可取的值:

  • none:允许两侧出现浮动元素(默认)。
  • left:左不允许浮动元素。
  • right:右侧不允许浮动元素。
  • both:左右两侧均不允许浮动元素。

页面B中,对box3清除浮动。

1
2
3
4
5
6
7
8
<body>
<div class="box1">
<div class="box2"></div>
<div class="box2"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>

页面A

1
2
3
4
5
6
7
8
9
10
.box2 {
margin: 0 10px;
float: left;
width: 100px;
height: 100px;
background: #b72afc;}
.box3 {
width: 360px;
height: 50px;
background: #23d2fc;}

页面B

1
2
3
4
5
6
7
8
9
10
11
.box2 {
margin: 0 10px;
float: left;
width: 100px;
height: 100px;
background: #b72afc;}
.box3 {
clear: both; /*或者用clear:left*/
width: 360px;
height: 50px;
background: #23d2fc;}

对父容器使用伪类清除浮动

1
2
3
4
5
.clearfix::after {
content: ".";
display: block;
height: 0;
clear: both;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.box1::after { 
content: ".";
display: block;
height: 0;
clear: both;}
.box2 {
margin: 0 10px;
float: left;
width: 100px;
height: 100px;
background: #b72afc;}
.box3 {
width: 360px;
height: 50px;
background: #23d2fc;}