1. 固定定位(position:fixed;)
(1) 固定定位解释参考文档:
https://developer.mozilla.org/zh-CN/docs/Learn/CSS/CSS_layout/%E5%AE%9A%E4%BD%8D
(2) 固定定位特性:
a. 如果不设定任何偏移值,元素位置不会有任何改变
b. 让元素完全脱离文档流 (不会对文档流里的元素造成布局上的影响)
c. 让内联元素支持宽高
d. 不设置宽度的时候,宽度由内容撑开
e. 提升层级(高于浮动元素)
f. 固定定位始终相对于document发生偏移,并且会固定在屏幕中
g. 触发BFC
注意:固定定位的特性和绝对定位基本一致,不同的是,固定定位始终相对于document发生偏移,并且会固定在屏幕中 ,在做类似返回顶部时常用
<div class="main" id="top">顶部</div> <div class="main" id="first">第一部分</div> <div class="main" id="second">第二部分</div> <div class="main" id="third">第三部分</div> <div class="box"> <a href="#first">第一部分</a> <a href="#second">第二部分</a> <a href="#third">第三部分</a> <a href="#top">返回顶部</a> </div>
<style>
.main {
height: 200px;
300px;
border: 4px solid #4b086d;
margin: 0 0 800px 50px;
font: 50px/200px '';
text-align: center;
}
.box {
100px;
height: 400px;
background: #5ccce7;
position: fixed;
right: 0;
top: 50%;
}
.box a {
display: inline-block;
100%;
background: #999;
color: #fff;
text-align: center;
margin: 5px 0;
}
body {
margin: 0;
height: 3000px;
}
</style>
2. 固定定位 position:relative
相对定位的元素是在文档中的正常位置偏移给定的值,但是不影响其他元素的偏移
div class="box" id="one">One</div> <div class="box" id="two">Two</div> <div class="box" id="three">Three</div> <div class="box" id="four">Four</div> .box { display: inline-block; 100px; height: 100px; background: red; color: white; } #two { position: relative; top: 20px; left: 20px; background: blue; }
3.绝对定位 postition:absolute
absolute:元素框从文档流中完全删除,并相对于其其包含块定位。生成绝对定位的元素,相对于static定位以外的第一个父元素进行定位。元素的位置通过“left","top""right""bottom"属性进行规定。。当这样的祖先元素不存在时,则相对于ICB(inital container block, 初始包含块)
<div class="box" id="one">One</div> <div class="box" id="two">Two</div> <div class="box" id="three">Three</div> <div class="box" id="four">Four</div> .box { display: inline-block; background: red; 100px; height: 100px; float: left; margin: 20px; color: white; } #three { position: absolute; top: 20px; left: 20px; }