CSS 居中

一. 水平居中

  1. margin: 0 auto
<div class="box"></div>

<style>
.box {
  width: 200px;
  height: 100px;
  margin: 0 auto;
  background-color: pink;
}
</style>
  1. 当子元素 display: inline-block 时,父元素 text-align: center,可控制子元素水平居中。
<div class="wrap">
  <div class="box"></div>
</div>

<style>
.wrap {
  text-align: center;
}
.box {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: pink;
}
</style>

text-align: center 在块级父容器中让行内元素居中,inline/inline-block/inline-table/inline/flex 等类型的元素实现居中。

二. 垂直居中

  1. 单行,对于单行行内或文本元素,只需为它们添加等值的 padding-toppadding-bottom

  2. 在已知文本不会换行的时候,可以 line-height = height 来实现垂直居中。

  3. 多行文本垂直居中
    3.1 方法一



    3.2 方法二:使用 flex

.box {
  display: flex;
  align-items: center;
  width: 100px;
  height: 100px;
  background-color: #ccc; 
}
  1. 当父元素没有固定高度时,可以采用 幽灵元素(ghost element)的非常规解决方式:在垂直居中的元素上添加伪元素,设置伪元素的高等于父元素的高,然后为子元素添加 vertical-align: middle;
    // 待定

三. 水平垂直居中

绝对定位元素的水平垂直居中

  1. 宽高固定,绝对定位,top: 50%; left: 50%; 左上 margin 为自身宽高一半
<div class="box"></div>

<style>
.box {
  width: 200px;
  height: 100px;
  position: absolue;
  left: 50%;
  top: 50%;
  margin-top: -50px;
  margin-left: -100px;
  background-color: pink;
}
</style>
  1. 同上,使用 css3 里的 transform 代替 margin。可以不设宽高。
<div class="box"></div>

<style>
.box {
  position: absolue;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: pink;
}
</style>
  • transform 里的 translate偏移的百分比值是相对于自身大小的

  • translate() 方法,根据 左(X轴)顶部(Y轴) 位置给定的参数,从当前元素位置移动,如:translate(50px,100px)是从左边元素移动 50 个像素,并从顶部移动 100 像素。

  1. margin:auto
.box {
  position: absolute;
  background: red;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 200px;
  height: 100px;
}

利用 flex 布局的水平垂直居中

需要注意,flex 垂直居中相对于父元素高度。

<div class="wrap">
   <div class="box"></div>
</div>

<style>
.wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.box {
  width: 200px;
  height: 100px;
  background-color: red;
}
</style>

利用 grid 布局的水平垂直居中

方法一:父元素设置 display: grid; justify-items: center; align-items: center;
方法二:父元素设置 display: grid;,子元素设置 justify-self: center; align-self: center;

.wrap {
  display: grid;
  height: 100vh;
  background-color: #ee3;
/*   justify-items: center;
  align-items: center; */
}
.box {
  background-color: #c9c;
  width: 100px;
  justify-self: center;
  align-self: center;
}

参考资料 :
小tip: margin:auto实现绝对定位元素的水平垂直居中

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,790评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 8,204评论 3 30
  • 选择qi:是表达式 标签选择器 类选择器 属性选择器 继承属性: color,font,text-align,li...
    wzhiq896阅读 1,788评论 0 2
  • 选择qi:是表达式 标签选择器 类选择器 属性选择器 继承属性: color,font,text-align,li...
    love2013阅读 2,327评论 0 11
  • 起因 今天早晨坐享的时候,发现心情不太正常,是一种类似于烦恼的东西……对,是焦虑与不耐烦。睁开眼之后想记录下来,却...
    一般的路人丙阅读 2,086评论 0 0