text-align:center;
只要父元素设置该属性值,全部的行内子元素都会水平居中。且该属性有继承性布局
margin: 0 auto;
具备宽度的块级元素设置上面属性后就会在父元素中左右居中flex
.parent { position: relative; }
.children { width: 150px; height: 150px; background: #d780c9; position: absolute; left: 50%; margin-left: -75px; }
将父元素定位为 relative,子元素定位为 absolute,子元素就会相对于父元素进行定位,left 设为50%,margin-left 为宽度的一半,由此实现了左右居中。spa
该方法可实现垂直水平居中.net
.parent { display: relative; } .children { width: 150px; height: 150px; background: #d780c9; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
将子元素设为 position: absolute + (left=0+top=0+right=0+bottom=0)+ margin: auto,将父元素定位为 relative,由此子元素将会在父元素中垂直水平居中。若是父元素没有相对定位,则该元素相对于整个窗口垂直水平居中。code
.children { position: absolute; left: 50%; transform: translateX(-50%); }
.parent{ display: flex; justify-content: center; }
.children { display: table; margin: 0 auto; }
在某一元素中设置display为table,左右外边距自动,由此可实如今父元素中左右居中。orm
.parent { text-align: center; } .children { display: inline-block; /*或者: display: inline; */ }
子元素设为行内元素,父元素经过属性 text-align 设置行内元素居中。blog
.parent{ display: flex; align-items: center; }
.parent { position: relative; } .children { width: 150px; height: 150px; position: absolute; top: 50%; margin-top: -75px; }
.parent{ display: table-cell; vertical-align: middle; }
由此父元素中的子元素所有都实现了垂直居中继承
参考上面的2.3get
参考上面的3.1it
详细参考:https://blog.csdn.net/dengdongxia/article/details/80297116