css中div盒子居中方式

方案一:Transforms 变形

父元素-相对定位

position: relative;

子元素-绝对定位

position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

方案二:弹性布局

父元素:

display: flex;
justify-content: center; /*子元素水平居中*/
align-items: center; /*子元素垂直居中*/

方案三:已知元素的高宽

父元素-相对定位

position: relative;

子元素-绝对定位

#div{
    background-color:#6699FF;
    width:200px;
    height:200px;
    position: absolute;        /*父元素需要相对定位*/
    top: 50%;
    left: 50%;
    margin-top:-100px ;   /*二分之一的height,width*/
    margin-left: -100px;
}

方案四:未知元素的高宽

父元素-相对定位

position: relative;

子元素-绝对定位

  #div{
    background-color: #6699FF;
    margin:auto;
    position: absolute;        /*父元素需要相对定位*/
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    }

猜你喜欢

转载自blog.csdn.net/weixin_42611825/article/details/126573557