<div class="big" id="big">
<div class="small" id="small"></div>
</div>
定位:
1、 前提是需要知道宽高的具体值
.big { width: 500px;height: 500px;background: green; position: relative;margin: 0 auto;}
.small { width: 200px;height: 100px;background: salmon;position: absolute;top: 50%;left: 50%;margin: -50px 0 0 -100px;}
2、 一定要有宽高,但不需要知道宽高的具体值
.big { width: 500px;height: 500px;background: green; position: relative;margin: 0 auto;}
.small { width: 200px;height: 100px;background: salmon;position: absolute;top: 0;left: 0;bottom: 0;right: 0;margin: auto;}
3 、不需要宽高,由内容撑开,但是兼容性不好
.big { width: 500px;height: 500px;background: green;position: relative;margin: 0 auto;}
.small { width: 200px;height: 100px;background: salmon;position: absolute;top:50%;left:50%;transform: translate(-50%,-50%);}
display:flex(兼容性不好)
.big { width: 500px;height: 500px;background: green;margin: 0 auto;display: flex;justify-content: center;align-items: center;}
.small { width: 200px;height: 100px;background: salmon;}
justufy-content:X轴的对齐方式
align-items:Y轴的对齐方式
JavaScript
css代码:
.big { width: 500px;height: 500px;background: green;margin: 0 auto;position: relative;}
.small { width: 200px;height: 100px;background: salmon;}
js代码:
window.onload = function () {
var big = document.getElementById("big");
var small = document.getElementById("small");
var bigWidth = big.offsetWidth;
var bigHeight = big.offsetHeight;
var smallHeight = small.offsetHeight;
var smallWidth = small.offsetWidth;
small.style.position = "absolute";
small.style.top = (bigHeight-smallHeight)/2 + "px";
small.style.left = (bigWidth-smallWidth)/2 + "px";
}
display:table-cell(基本上不用这种方法)
.big { width: 500px;height: 500px;background: green;display: table-cell;text-align: center;vertical-align: middle;}
.small { width: 200px;height: 100px;background: salmon;display: inline-block;}