首先父盒子包住子盒子
<body> <div class="outbox"> <div class="box"></div> </div> </body>
方法一:设置距父盒子的margin-top/margin-left为父盒子宽度或长度-子盒子宽度或长度一半
<style> *{ padding: 0; margin: 0; } .outbox{ width:100px; height: 100px; background: chartreuse; border: 1px solid black; margin: auto; } .box{ width: 50px; height: 50px; background: red; margin-top: 25px; margin-left: 25px; } </style>
方法二:绝对定位距左距上50% margin-top和margin-left 各为负的宽高一半拉回来
<style> *{ padding: 0; margin: 0; } .outbox{ width:100px; height: 100px; background: chartreuse; border: 1px solid black; margin: auto; position: relative; } .box{ width: 50px; height: 50px; background: red; position: absolute; left:50%; top:50%; margin-left: -25px; margin-top: -25px; } </style>
方法三:magin:auto absolute然后距离左右上下都为0
<style> *{ padding: 0; margin: 0; } .outbox{ width:100px; height: 100px; background: chartreuse; border: 1px solid black; margin: auto; position: relative; } .box{ width: 50px; height: 50px; background: red; position: absolute; margin: auto; top:0; left:0; bottom:0; right:0 } </style>
方法四:利用table-cell(注意:只能用于ie8及其以上)属性 将父元素表格形式呈现 vertical-align显示为上下居中middle
<style> *{ padding: 0; margin: 0; } .outbox{ width:100px; height: 100px; background: chartreuse; border: 1px solid black; margin: auto; display: table-cell; vertical-align: middle; } .box{ width: 50px; height: 50px; background: red; margin: auto; } </style>
方法五:弹性布局居中 align-item:center垂直居中 justify-content:水平居中
<style> *{ padding: 0; margin: 0; } .outbox{ width:100px; height: 100px; background: chartreuse; border: 1px solid black; margin: auto; display:flex; align-items: center; justify-content: center; } .box{ width: 50px; height: 50px; background: red; } </style>
绝对定位的方式fixed可以如法炮制;当然我认为也可以用display:inline-block