玩转 css 居中

文字居中

文字的水平居中

  1. 对于非 inline 元素内的文字水平居中都可以通过 text-align: center; 完成。

  2. 也可以设置 margin: 0 auto;

文字(单行)的垂直居中

这种场景通常在修正 input 框光标和文字的位置。设置 line-height 的值等于 height 即可。

文字(单行)的相对居中

/Users/alex/Desktop/24319F76-DE76-4A5A-840D-8EC7C0C43882.png
例如图中的状况,需要文字相对于图片的垂直居中,通过对图片设置vertical-align: middle;即可。vertical-align 其实可以完成多种相对对其,例如 top,baseline 等等。

元素居中

内部元素的宽高已知

本方法应该是用的非常多的了,直接看代码吧

.outer {
    width: 100%;
      height: 500px;
    position: relative;
}
.inner {
  position: absolute;
  width: 200px;
  height: 200px;
  top: 50%;
  left: 50%;
  margin: -100px 0 0 -100px;
  background-color: blue;
}

上面方法在 css 中加入 calc 之后可以做如下优化 (安卓 4.3 以上,IE9+)

.outer {
  width: 100%;
  height: 500px;
  position: relative;
}
.inner {
  position: absolute;
  width: 200px;
  height: 200px;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
  background-color: blue;
}

外部元素的高度已知

html:

<div class="outer">
  <div class="inner">
    <p>asjdhajshdkjhakjdshk</p>
    <p>sdalskjdkajls</p>
  </div>
</div>
  1. table 搭配 table-cell 的方法

.outer {
  width: 100%;
  height: 300px;
  display: table;
  text-align: center;
}
.inner {
  display: table-cell;
  vertical-align: middle;
}
  1. translate 方法(IE9 以上)

.outer {
  width: 100%;
  height: 500px;
  position: relative;
}
.inner {
  position: absolute;
  top: 50%; 
  left: 50%;
  transform: translate(-50%, -50%);
}
  1. flex 方法
    该方法就非常简单了,只需要设置 outer

.outer {
  width: 100%;
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
}

内外元素高度均已知

html 模版沿用上面

.outer {
  width: 100%;
  height: 500px;
  position: relative;
  text-align: center;
}
.inner {
  height: 100px;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

我相信本文绝对不是最全的 css 居中方式,希望各位大神们补充起来。

    原文作者:flashback
    原文地址: https://segmentfault.com/a/1190000005801078
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞