今天我们来分享web前端CSS定位中的position:absolute绝对定位的应用场景案例的相关场景!
绝对定位是CSS中非常中啊哟的知识点,接下来我我们会通过7个不同的层面结合7个不同的案例来展开讲解!
绝对定位元素的特性
- 使元素完全脱离文档流,将释放自己的位置
- 元素的层级提升,会覆盖在其它元素上
- 离自己最近的定位父元素进行位置调整,如果没有定位的父元素,则相对body进行位置调整
- 元素支持宽高设置
- margin:auto;水平居中失效。可以通过left与margin-left控制元素水平居中
- 定位元素未设置宽高情况下,同时设置top和bottom会改变元素高,同时设置left和right会改变元素宽
绝对定位元素常见用法合集
- top、bottom以及left、right 优先级(案例1)
- 相对于直接父元素定位(案例2)
- 相对父元素的父元素定位(案例3)
- 相对于body定位(案例4)
- 子元素自适应父元素宽高(案例5)
- 设置元素水平垂直居中(案例6)
- 改变元素的层级关系(案例7)
1、top、bottom以及left、right 优先级
如果元素添加宽高,同时设置top与bottom属性,会以top值为主。
如果同时设置left和right属性,以left为主。
<style type="text/css">
html,body{margin:0;}
.box{
width:100px;
height:100px;
margin: 50px auto;
background-color: pink;
position: relative;/*相对定位*/
}
.box .item{
width:50px;
height: 50px;
position: absolute;/*绝对定位*/
left:-20px;/*与相对定位元素左边距离*/
top:-20px;/*与相对定位元素顶部距离*/
bottom:0px;/*不生效*/
right:0px;/*不生效*/
background-color:skyblue;
}
</style>
2、相对于直接父元素定位
相对于直接父元素定位案例是太多太多,下图列举了几个
其中图1鼠标滑动悬浮效果 源码
<style>
body,h3{
margin:0;
padding:0;
}
.music{
width: 150px;
height: 150px;
margin:100px auto;
position: relative;
}
.music h3{
height: 35px;
line-height: 35px;
width: 100%;
background-color: rgba(0,0,0,0.5);
color:#fff;
position: absolute;
left:0px;
bottom:0px;
font-size: 14px;
font-weight: 100;
white-space: nowrap;
overflow: hidden;
text-o