html代码:

<div class="box">
<div class="box-item">
文字
</div>
</div>

css样式:

一、水平居中

.box-item{
text-align:center;
}

  *一般用于文字以及inline-block/inline水平居中 ,设置该值表示box-item内文字居中对齐

.box-item{
margin:0 auto;
}

  *一般用于类似div的block水平居中,表示box-item整个div在box内水平居中对齐

二、垂直居中

  • 高度等于行高,适合单行文字居中对齐
.box-item{
line-height:30px;
height:30px
}
  • margin为高度一半
.box{
width:100%;
height:100%;
margin:;
padding:0
}
.box-item{
width:100px;
height:100px;
border:1px solid #ccc;
position:relative;
top: 50%;
margin: -150px auto 0 auto;
}
  • 前一种方式的改良版
.box{
width:100%;
height:100%;
margin:;
padding:0
}
.box-item{
width:100px;
height:100px;
border:1px solid #ccc;
position:relative;
top: 50%;
margin:0 auto;
transform: translateY(-50%);
}
  • align-items存在兼容性问题
.box {
display: flex;
align-items: center;
justify-content: center;
}
.box-item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
  • 兼容性较好的几种:
.box-item{
margin:auto;
width:100px;
height:100px;
position:absolute;
top:;
left:;
bottom:;
right:;
}
.box{
position: relative;
height:100%;
width:100%;
} .box-item{
width: 100px;
height: 100px;
overflow: auto;
margin: auto;
position: absolute;
top:; left:; bottom:; right:;
}
.box{
text-align: center;
overflow: auto;
height:100%;
} .box:after,.box-item{
display: inline-block;
vertical-align: middle;
}
.box:after {
content: '';
height: 100%;
margin-left: -0.25em;
} .box-item{
max-width: 99%;
}
  • 表格法
.box{
display:table;
width:100%;
height:100%;
}
.box-item {
display: table-cell;
vertical-align: middle;
text-align: center;
}

最新文章

  1. url中的特殊符号含义
  2. Linux文件权限概念
  3. Yii里获取当前controller和action的id
  4. 通过data:image/png;base64把图片直接写在src里
  5. Doragon Kuesuto 1.0
  6. 网站中的专题页或者tag聚合页的权重不错
  7. 用C++ 设计一个不能被继承的类
  8. 【JS模式】单体模式
  9. Hadoop入门--HDFS(单节点)配置和部署 (一)
  10. C primer plus 读书笔记第四章
  11. 站在OC的基础上快速理解Swift的类与结构体
  12. php 编程效率(3)
  13. 使用ML.NET实现白葡萄酒品质预测
  14. maven教程全攻略
  15. bzoj1026: [SCOI2009]windy数(数位dp)
  16. 让InstallShield 2015 Limited Edition for Visual Studio 2015生成的setup.exe双击时以管理员权限运行
  17. [UE4]键盘鼠标输入事件
  18. 百度前端技术学院-task2.18-2.19源码以及个人总结
  19. Gatling新一代压力测试工具,新一代服务器性能测试工具Gatling
  20. Python&#160;利用Python编写简单网络爬虫实例2

热门文章

  1. typedef 函数指针的用法
  2. Redis 教程笔记
  3. 快速排序(java)
  4. Polygon
  5. 错误:(26, 13) Failed to resolve: com.android.support:appcompat-v7:27.+
  6. ios之Block研究
  7. 微信小程序开发之下拉菜单
  8. php查询内存信息
  9. 数据库路由中间件MyCat - 源代码篇(6)
  10. JavaScript 原型的实际应用之实现一个 jQuery