简单总结position定位和元素水平垂直居中

position
position的属性值共有四个常用的:relative、absolute、fixed、static。
首先普及一下文档流的知识:显示元素对象在窗口排列时所占用的位置,自上而下,从左到右。脱离文档流会影响其他元素的位置。

relative:相对定位,不脱离文档流,在文档流原先的位置进行位移。
absolute:绝对定位,脱离文档流,相对于最近的且不为static的父元素进行定位,把父元素当成参考物。无父级则相对于body定位。(body和浏览器窗口不是同一个概念,比如body可以设置宽高和边距)
fixed:固定定位,脱离文档流,相对于浏览器窗口定位,不随滚动条滚动而改变位置。
static:默认值,常用到的top、left、bottom、right会失效。

水平垂直居中
常用的四种元素水平垂直居中的方法:
a.父级相对定位,自级绝对定位

div{
    position:relative;
}
p{
    position:absolute;
    width:100px;
    height:100px;
    left:50%;
    top:50%;
    margin-left:-50px;   //这两行代码也可以替换成
    margin-top:-50px;    //transform:translate(-50%,-50%);
}

b.父级display:flex,子级margin:auto

div{
     display:flex;
}
p{
    margin:auto;
}

c.flex布局

div{
    display:flex;
    justify-content:center;   //主轴方向水平居中  
    align-items:center;        //交叉轴垂直居中  
}

d.定位+margin:auto法

div{
    position:relative;
}
p{
    poaitive:absolute;
    margin:auto;
    top:0;
    left:0;
    right:0;
    bottom:0
}

猜你喜欢

转载自blog.csdn.net/qq_37012533/article/details/84958566