1. 程式人生 > >塊級元素的水平、垂直居中

塊級元素的水平、垂直居中

分享圖片 tom height absolute 垂直 com eight wid htm

HTML:

 <div class="parent">
       <div class="child"></div>
 </div>

1.固定寬高

/* 利用calc */
.parent{
    position: relative;
    height: 500px;
    width: 300px;
    margin: 0 auto;
    border: 1px solid pink;
}
.child{
    width: 200px;
    height: 100px;
    position: absolute
; left: -webkit-calc(50% - 100px); top: -webkit-calc(50% - 50px); background: skyblue; } /* 利用margin-left,margin-top */ .child{ width: 200px; height: 100px; position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -50px; background: skyblue; } /*
利用margin:auto */ .child{ width: 200px; height: 100px; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; background: skyblue; }

2.不固定寬高

/* 子元素的寬高暫時沒有去,可以自己去掉測試 */
.parent{
    position: relative;
    height: 500px;
    width: 300px;
    margin: 
0 auto; border: 1px solid pink; /* 使用transform時使用,預防出現0.5px */ -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; } /* 利用transform */ .child{ width: 200px; height: 100px; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); background: skyblue; }

效果圖:

技術分享圖片

塊級元素的水平、垂直居中