盒子水平居中的多种方法

<div class="big" id="big">
    <div class="small" id="small"></div>
</div>
3b528644-771d-42a7-a85a-78cdef938263.png

定位:

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;}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。