一.使用margin
内容;
1.只能用于水平居中
2.必须指定元素的宽度
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 } 6 7 .box2{ 8 width: 100px; 9 height: 100px; 10 background-color: #bfa; 11 12 /* 将元素的左右外边距设置为auto,元素即可在其包含块中自动水平居中 */ 13 margin: 0 auto; 14 15 }
二.使用绝对定位
1.1.必须要指定元素的宽度和高度
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 6 position: relative; 7 } 8 9 .box2{ 10 width: 100px; 11 height: 100px; 12 background-color: #bfa; 13 14 15 16 /* 通过绝对定位来设置元素的居中 */ 17 position: absolute; 18 19 /* 四个偏移量都设置为0 */ 20 top: 0; 21 left: 0; 22 bottom: 0; 23 right: 0; 24 25 margin: auto; 26 27 }
三.使用表格(display:xxxx)
1.不需要指定元素的宽度高度(inline-block)
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 /* 将父元素转换为单元格 */ 6 display: table-cell; 7 vertical-align: middle; 8 } 9 10 .box2{ 11 width: 100px; 12 height: 100px; 13 background-color: #bfa; 14 }
四。使用变形
1.不需要设置元素的宽度和高度
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 6 position: relative; 7 } 8 9 .box2{ 10 width: 100px; 11 height: 100px; 12 background-color: #bfa; 13 14 15 left: 50%; 16 top:50%; 17 transform: translateX(-50%) translateY(-50%); 18 19 }
五。使用弹性盒flex
1.不需要设置元素的宽度和高度
2.会使所有的子元素都在父元素中居中
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 6 display: flex; 7 8 justify-content: center; 9 align-items: center; 10 11 12 } 13 14 .box2{ 15 width: 100px; 16 height: 100px; 17 background-color: #bfa; 18 }