一、直接及算法
- margin =(父盒子宽度 - 子盒子宽度)/ 2
二、绝对定位法 2. 四边距0 和 margin自适应
Document body { margin: 0; } div { width: 300px; height: 300px; background-color: green; } /*居中关键代码*/ .box { margin: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; }- 绝对定位百分比 和 负margin
- 绝对定位 和 translate
三、Flex布局 5. 父盒子flex 和 justify-content,align-items属性
Document /* * html和body需要撑满浏览器 * 如果父盒子是div则不需要这段代码 */ body, html { height: 100%; width: 100%; margin: 0; } /*居中关键代码*/ body { display: flex; justify-content: center; align-items: center; } div { width: 300px; height: 300px; background-color: red; }6.父盒子flex 和 子盒子margin自适应
Document /* * html和body需要撑满浏览器 * 如果父盒子是div则不需要这段代码 */ body, html { height: 100%; width: 100%; margin: 0; } div { width: 300px; height: 300px; background-color: purple; } /*居中关键代码1*/ body { display: flex; } /*居中关键代码2*/ .box { margin: auto; }四、table-cell 7. 父盒子设置table-cell 和 vertical-align,text-align属性
.parent { width: 500px; height: 500px; background-color: cyan; } /* 居中关键代码 */ .center { display: table-cell; vertical-align: middle; text-align: center; } .child { width: 200px; height: 200px; display: inline-block; background-color: red; }