一、什么是position属性
CSS position属性是用来定义HTML元素的定位方式的,它有四个属性值:static(默认值)、relative、absolute、fixed。通过设置不同的位置属性值、top、right、bottom、left属性,可以让元素按照我们想要的位置进行定位。
二、position属性的四个属性值
1. static:
static是默认属性值,也就是说,如果我们没有设置元素的position属性的值时,默认是static。
在static的状态下,top、right、bottom、left这些属性都没有任何作用,元素按照默认的位置放置在HTML文档流中。
#box{
position: static; //默认属性值,可以不写
}
2. relative:
相比于static,relative属性值使得我们可以通过top、right、bottom、left属性,将元素相对自身的初始位置进行移动。
#box{
position: relative;
top: 10px;
left: 20px;
}
3. absolute:
absolute属性值可以让元素脱离文档流,相对于祖先元素(即其上一级并且设置为非static属性值)进行定位。
#parent{
position: relative;
}
#child{
position: absolute;
top: 50px;
left: 50px;
}
4. fixed:
fixed属性值是相对于浏览器窗口进行定位,元素的位置不会随着滚动条的滚动而改变。
#box{
position: fixed;
top: 0;
left: 0;
}
三、如何居中一个div
1.水平居中:
想要让一个div水平居中,可以通过设置它的margin-left和margin-right为auto实现。
#box{
width: 200px;
height: 200px;
background-color: orange;
position: relative;
margin-left: auto;
margin-right: auto;
}
2.垂直居中:
垂直居中有多种实现方式,以下列举两种:
(1)通过设置absolute和transform属性值实现:
#parent{
position: relative;
}
#child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
(2)通过设置display:flex属性值实现:
#parent{
display: flex;
align-items: center;
justify-content: center;
}
#child{
width: 200px;
height: 200px;
background-color: yellow;
}
四、兼容性问题
1. IE 6或更早的版本不支持fixed属性值。
2. 在父元素没有设置定位属性时,子元素的绝对定位可能会受到body或html的影响,因此请务必设置父元素的定位属性值。
3. z-index属性值的问题。
由于css的堆叠顺序,父元素会覆盖相对于其定位的子元素,因此应当为子元素设置z-index属性值,将其置于父元素的上面。
#parent{
position: relative;
}
#child{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
top: 50px;
left: 50px;
z-index: 1;
}
五、总结
position属性是CSS中一种非常强大的定位方式,它可以让HTML元素按照我们想要的位置进行定位,并有多个属性值可以进行选择。在使用时需要注意兼容性问题、设置父元素的定位属性值以及z-index属性值的问题,这些问题在实际开发中应该是比较常见的,因此需要特别注意。
原创文章,作者:SKBFZ,如若转载,请注明出处:https://www.506064.com/n/329032.html
微信扫一扫
支付宝扫一扫