实现一个盒子的水平/垂直居中的几种方法

75 阅读1分钟

如何实现一个盒子的水平/垂直居中?

方法一:利用定位 .parent { /*父盒子相对定位 */ position: relative; width: 300px; height: 300px; margin: 100px auto; background-color: purple; } .child { width: 100px; height: 100px; background-color: skyblue; /*子盒子绝对定位,margin给子盒子的宽高的一半 */ position: absolute; left: 50%; top: 50%; margin-top: -50px; margin-left: -50px; } </style>

方法二:利用margin:auto <style> .parent { /*父盒子相对定位 */ position: relative; width: 300px; height: 300px; margin: 100px auto; background-color: purple; } .child { width: 100px; height: 100px; background-color: skyblue; /*子盒子绝对定位 */ position: absolute; margin:auto; top: 0; bottom: 0; left: 0; right: 0; } </style>

方法三:利用transform <style> .parent { width: 300px; height: 300px; background-color: purple; margin: 100px auto; /*设置相对定位*/ position: relative; } .child { width: 100px; height: 100px; background-color: skyblue; /*子盒子绝对定位*/ position: absolute; top: 50%; left:50%; transform: translate(-50%,-50%); } </style>

方法四:利用display:table-cell ` .parent { width: 300px; height: 300px; border: 1px solid #000; display: table-cell; vertical-align: middle; text-align: center; } .child { width: 100px; height: 100px; border: 1px solid #999; background-color: skyblue; display:inline-block; }

`