CSS之元素居中

水平方向

行内元素

.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...

相关文章
相关标签/搜索