.center-children { text-align: center; }
适用于行内元素,行内块元素。css
.center-children { margin: 0 auto; }
margin左右设置为auto,前提条件:元素自己须要设置宽度。ide
.center-children{ display:inline-block; } .center{ text-align: center; }
将块级元素设置为行内元素,父元素内容居中。
还有一种方法是用flex,但只能兼容IE10+。布局
与块级元素同样,只是设置多个块级元素。flex
.center-children { padding-top: 30px; padding-bottom: 30px; }
这里设置上下padding同样。只能用于单行的行内元素。ui
.center-children { height: 100px; line-height: 100px; }
行高与高度相等。code
.center{ display:table; } .center-children{ display:table-cell; vertical-align:middle; }
父元素设置为table,子元素设置为table-cell。垂直居中。orm
.center{ display: flex; justify-content: center; flex-direction: column; height: 400px; }
直接使用flex,注意兼容性。get
.parent { position: relative; } .child { position: absolute; top: 50%; height: 100px; margin-top: -50px; }
使用绝对定位。须要知道子元素的高度。页面布局
.parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); }
使用绝对定位。不须要知道子元素的高度。
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
使用flex。it
.parent { position: relative; } .child { width: 300px; height: 100px; padding: 20px; position: absolute; top: 50%; left: 50%; margin: -70px 0 0 -170px; }
思路跟以前同样。使用绝对定位。须要知道高度。
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
使用绝对定位。不须要知道高度。
.parent { display: flex; justify-content: center; align-items: center; }
使用flex。
以上是页面布局中,常常须要用到的各类居中方法,网上也有不少技巧,这里就简单的总结概括,用到时能够选用合适的方案。整体来讲,在兼容性(兼容IE10以上)容许的条件下,优先选择flex方法,实现简单。
http://howtocenterincss.com/
https://css-tricks.com/center...