我们都知道在web页面开发时,有时我们灵活的运用css的定位postion属性进行布局时可以实现很好的效果,本文我们总结了一下position知识点,及平常比较常用的地方,希望对学习css的朋友可以参考。ec(2);
首先我们对postion属性进行详解。
在CSS3中,对于postion是这么描述的
总结如下:
static 是默认布局,设置top\left。。属性不会有作用。
relative是相对布局,设置的top\left。。会相对文件中的控件。
absolute是绝对定位,设置的top\left。。会相对整个页面而定。
fixed是相对浏览器窗口定位,设置的top/left属性,是相对于浏览器窗口的位置。
除此之外,经过我代码测试:
1.如果top\left。。其中某属性缺省,absolute,fixed布局的位置,会相对于父控件的位置进行改变。
2.relative相对定位,如果有父控件,相对的是最近的一个父控件,而非同层最近的一个父控件。其次是兄弟控件。
3.static对其他的遮盖层没有影响。
接着我们来通过代码证明以上结论:
情况1
HTML:
one
two
tree
CSS:#zero{
width:200px;
height: 200px;
margin: 100px 500px;
background: black;
z-index: 0;
}
#one{
width: 100px;
height: 100px;
position: relative;
top: 50px;
left:20px;
background: red;
z-index: 1;
}
#two{
width: 100px;
height: 100px;
position: absolute;
top: 190px;
background: yellow;
z-index: 2;
}
#tree{
width: 100px;
height: 100px;
position: fixed;
top: 250px;
left: 600px;
background: deepskyblue;
z-index: 3;
}
在此大家可以看出来id为one的p是相对父控件的布局。
情况2:
CSS:#first{
width: 200px;
height: 200px;
background: black;
margin-top: 100px;
z-index: 1;
}
#second{
margin-top: 10px;
margin-left:10px;
width: 150px;
height: 150px;
background: yellow;
z-index:2;
}
#thrid{
width: 100px;
height: 100px;
position:relative;
background: red;
top: 30px;
left: 30px;
z-index: 1;
}
HTML:
从这里可以看出当relative定位是相对最近一个父控件的,而非同层父控件。
情况3:如果没有父p:
HTML
CSS#out{
margin-top: 50px;
width: 200px;
height: 200px;
background: black;
z-index: 1;
}
#out1{
width: 200px;
height: 200px;
background: yellow;
position: relative;
z-index: 3;
top:10px;
}
通过这种情况,看出来 如果没有父控件,则relative定位是相对于兄弟关系的控件。
CSS3中对于z-index的描述
position开发中常见应用
1.网页两侧浮动窗口(播放器,置顶按钮,浮动广告,功能按钮等)
2.导航栏浮动置顶。
3.隐藏p实现弹窗功能(通过设置p的定位和z-index控制p的位置和出现隐藏)
其中1,3较为简单,通过简单的设置position=fixed,以及top left,z-index就能实现,此处不做说明
情况2:
通过调用js函数判断滚动条所在的位置,超过导航栏距离顶部的高度时就设置position为fix固定导航栏位置,否则position为static,maring等属性不变。
JS:var mt = 0;
window.onload = function () {
var myp = document.getElementById("myp");
var mt = myp.offsetTop;
window.onscroll = function () {
var t = document.documentElement.scrollTop || document.body.scrollTop;
if (t > mt) {
myp.style.position = "fixed";
myp.style.margin = "0";
myp.style.top = "0";
}
else {
myp.style.margin = "30px 0";
myp.style.position = "static";
}
}
}
HTML:
设置合适的CSS控制自己想要的样式。
相关推荐: