相对定位跟绝对定位(相对定位relative、绝对定位absolute、固定定位fixed)
导读:注:默认情况下的定位是 postion:static; 使用定位时,常常使用偏移量对位置进行描述:left、right、top、bottom 定位时,使用z-indent可以元素的堆叠顺序,例:z-indent:1,出现在上层(...
注:默认情况下的定位是 postion:static;
使用定位时 ,常常使用偏移量对位置进行描述:left 、right 、top 、bottom 定位时 ,使用z-indent可以元素的堆叠顺序 ,例:z-indent:1 ,出现在上层(z-index 仅能在定位元素上奏效)相对定位relative
相对定位的参考物是元素的初使位置
相对定位的特点:
不影响元素本身的特性 元素不脱离文档流 相对于原位置进行偏移 div{ width: 100px; height: 100px; margin: 10px; font-size: 40px; text-align: center; line-height: 100px; background-color: orange; } div:nth-of-type(2){ position: relative; left: 100px; } <div>1</div> <div>2</div> <div>3</div>绝对定位absolute
绝对定位的参考物是:距离最近的使用了定位的父级 ,父级都没有使用时找body
绝对定位的特点:
元素脱离文档流 行元素支持所有的css样式 块元素由内容撑开宽高 清除子级浮动 div{ width: 100px; height: 100px; margin-bottom: 10px; font-size: 40px; text-align: center; line-height: 100px; background-color: orange; } div:nth-of-type(2){ position: absolute; left: 100px; } <div>1</div> <div>2</div> <div>3</div> .one{ background-color: orange; width: 300px; height: 300px; position: relative; } .two{ background-color: greenyellow; width: 200px; height: 200px; position: absolute; top: 50px; left: 50px; } .three{ background-color: skyblue; width: 100px; height: 100px; position: absolute; top: 50px; left: 50px; } <div class="one"> <div class="two"> <div class="three"></div> </div> </div>使用定位实现万能居中:
.background{ width: 100vw; height: 100vh; background-color: rgba(0, 0, 0, .7); } .background div{ width: 300px; height: 200px; background-color: #fff; /* 以下代码实现万能居中 */ position: absolute; left: 50%; top: 50%; margin-left: -150px; margin-top: -100px; } <div class="background"> <div> 万能居中公式:<br> position: absolute;<br> left: 50%;<br> top: 50%;<br> margin-left: -width/2;<br> margin-top: -height/2;<br> </div> </div>固定定位fixed
参考物:浏览器窗口
固定定位的特点:
脱离文档流 清除子级浮动固定定位的实现 可以使页面中的某个元素不随浏览器的滚动而消失 ,例如 导航栏的固定实现
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!