如何使一个盒子水平垂直居中

189 阅读1分钟

一、直接及算法

  1. margin =(父盒子宽度 - 子盒子宽度)/ 2
Document .parent { width: 600px; height: 600px; background-color: darkcyan; /* 如果没有这一行,内部的盒子margin-top属性会失效(也可以设置子盒子display: inline-block;) */ overflow: hidden; } .child { width: 300px; height: 300px; background-color: darkgreen; } /* 居中关键代码(必须知道内外盒子的大小) */ .center { /* margin的值为(parent.width-child.width) / 2 */ margin: 150px; }

二、绝对定位法 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; }
  1. 绝对定位百分比 和 负margin
Document div { width: 300px; height: 300px; background-color: orange; } /* * 居中关键代码 (需要知道盒子的高度和宽度) */ .box { position: absolute; left: 50%; top: 50%; /* 两种写法均可 */ /* margin: -150px -150px; */ margin-top: -150px; margin-left:-150px; }
  1. 绝对定位 和 translate
Document div { width: 300px; height: 300px; background-color: cyan; } /*居中关键代码*/ .box { position: absolute; transform: translate(-50%, -50%); left: 50%; top: 50%; }

三、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; }