设置居中样式

在css中居中效果可以分为:水平居中、垂直居中、水平垂直居中三种。最近小程序开发项目中也经常遇到居中效果设置问题,即简单归纳,以便后期使用。

水平居中:

方法1:margin和width实现水平居中
.center {
  width: 200rpx;
  margin-left: auto;
  margin-right: auto;
  /*或者margin: 0 auto;代替*/
}

这种是最简单的,但前提必须固定宽度值,margin-left & margin-right 设置为auto。但在IE下如果web页面未明确声明“!DOCTYPE”,要保证水平居中效果,则按如下进行设置即可:

/*html*/
<div class="container">我的页面</div>
body {
  text-align: center;
}
.container {
  text-align: left;
  width: 1024px;
  margin: 0 auto;
}
方法2: text-align实现水平居中
.center {
  text-align:center;
}

这种方法适用在块级父容器中让行内(inline)或类行内(inline-block/inline-table) 和 flex类型元素居中

方法3: inline-block 和 text-align 实现多个块元素水平居中
/*设置块元素*/ 
.center {
  display: inline-block;
  width: 80rpx;
  height: 100rpx;
}
 /*设置块元素的父容器*/
.father-container {
  text-align: center; /*注意:这个必须设置*/
  width: 100%;
  height: 100rpx;
}
方法4: fixed实现浮动居中
.center {
  position: fixed;
  display: flex;
  left: 0;
  right: 0;
  bottom: 100rpx;
  margin: 0 auto;
}
方法5: flex & justify-content 实现多个子元素水平居中
.father-container {
  display: flex;
  flex-direction: row; /*默认且必为主轴方向*/
  justify-content: center;
  height: 100rpx;
}

垂直居中:

方法1: inline-height 和 height 相等
.center {
  height: 100rpx;
  line-height: 100rpx;
  white-space: nowrap;
}

这种方法适用于文本不换行的情况下使用

方法2: padding-top 和 padding-bottom 相等
.center {
  padding-top: 30rpx;
  padding-bottom: 30rpx;
}

这种方法适合于单行行内或文本元素,对于多行文本可在其父容器增加如下设置:

.father-container {
  display: table-cell;
  vertical-align: center;
}
方法3: flex & justify-content 实现多个子元素垂直居中
.father-container {
  display: flex;
  flex-direction: column;/*必须为列*/
  align-items: center;
  height: 100rpx;
}

参考资料:
CSS--项目中那些居中问题
CSS 水平对齐(Horizontal Align)
整理: 子容器垂直居中于父容器的方案
解决 flex align-items: center 无法居中(微信小程序)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,353评论 1赞 92
  • H5移动端知识点总结 阅读目录 移动开发基本知识点 calc基本用法 box-sizing的理解及使用 理解dis...
    Mx勇阅读 4,890评论 0赞 26
  • 移动开发基本知识点 一.使用rem作为单位 html { font-size: 100px; } @media(m...
    横冲直撞666阅读 3,861评论 0赞 6
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 8,402评论 3赞 30
  • 人生若只如初见,何事秋风悲画扇。 等闲变却故人心,却道故人心易变。 这是大家耳熟能详的一首词,也是大家最深有体会的...
    3391阅读 338评论 1赞 1

友情链接更多精彩内容