学海无涯,不要沉浸在知识的海洋里,迷失本身。css
要知道本身想要什么,抓住重点,不忘初心。html
这个世界上百分之20的人,掌握着百分之80的财富。面试
接下来一系列教程,就带领你们抓住重点,一块儿作那百分之20的人。markdown
往期知识点回顾:oop
重点属性floatpost
为了制做更多复杂的布局,咱们须要讨论下 position 属性。它有一大堆的值,名字还都挺抽象的,接下来让咱们挨个学习一下。学习
static 是默认值。任意 position: static; 的元素不会被特殊的定位。一个 static 元素表示它不会被“positioned”,一个 position 属性被设置为其余值的元素表示它会被“positioned”。spa
.static {
position: static;
}
复制代码
relative 表现的和 static 同样,除非你添加了一些额外的属性。code
在一个相对定位(position属性的值为relative)的元素上设置 top 、 right 、 bottom 和 left 属性会使其偏离其正常位置。其余的元素的位置则不会受该元素的影响发生位置改变来弥补它偏离后剩下的空隙。
.relative1 {
position: relative;
}
.relative2 {
position: relative;
top: -20px;
left: 20px;
background-color: white;
width: 500px;
}
复制代码
一个固定定位(position属性的值为fixed)元素会相对于视窗来定位,这意味着即使页面滚动,它仍是会停留在相同的位置。和 relative 同样, top 、 right 、 bottom 和 left 属性均可用。
.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 200px;
background-color: white;
}
复制代码
absolute 是最棘手的position值。 absolute 与 fixed 的表现相似,可是它不是相对于视窗而是相对于最近的“positioned”祖先元素。若是绝对定位(position属性的值为absolute)的元素没有“positioned”祖先元素,那么它是相对于文档的 body 元素,而且它会随着页面滚动而移动。记住一个“positioned”元素是指 position 值不是 static 的元素。
绝对定位使用一般是父级定义position:relative定位,子级定义position:absolute绝对定位属性,而且子级使用left或right和top或bottom进行绝对定位。
.relative {
position: relative;
width: 600px;
height: 400px;
}
.absolute {
position: absolute;
top: 120px;
right: 0;
width: 300px;
height: 200px;
}
复制代码
inherit 值如同其余 css 属性的 inherit 值,即继承父元素的 position 值。
<!DOCTYPE html>
<html>
<head>
<title>postion元素</title>
<style>
.container {
position: relative;
border: 1px red solid
}
.nav {
position: absolute;
left: 0px;
width: 200px;
border: 1px blue solid
}
.section {
/* position is static by default */
margin-left: 200px;
border: 1px green solid
}
.footer {
position: fixed;
bottom: 0;
left: 0;
height: 70px;
background-color: white;
width: 100%;
border: 1px yellow solid
}
body {
margin-bottom: 120px;
}
</style>
</head>
<body>
<div class="container">
<div class="nav">
<li>.absolute</li>
<li>.absolute</li>
<li>.absolute</li>
</div>
<div class="section">
我是static
</div>
<div class="section">
我是static
</div>
<div class="section">
我是static
</div>
<div class="section">
我是static
</div>
<div class="footer">
我是 fixed
</div>
</div>
</body>
</html>
复制代码
使用fixed和absolute会脱离文档流。
脱离文档流,指的是元素脱离正常元素的布局排版规则,其余处于文档流中的盒子在计算布局排版时,会自动无视已脱离文档流的元素来进行定位。
(1)浮动会使元素脱离文档流,可是不会脱离文本流,在于其余盒子的文本内容计算布局的时候,仍是占位置的。
(2)绝对定位会使元素脱离文档流,同时也会脱离文本流, 在于其余盒子的文本内容计算布局的时候,不占位置。