如何将一个div水平垂直居中?4种方法做推荐
2024-10-18 13:17:30
方案一:
div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】,
兼容性:,IE7及之前版本不支持
div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
方案二:
div绝对定位水平垂直居中【margin 负间距】 这或许是当前最流行的使用方法。
div{
width:200px;
height: 200px;
background:green;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}
方案三:
div绝对定位水平垂直居中【Transforms 变形】
兼容性:IE8不支持;
div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:50%; /* 定位父级的50% */
top:50%;
transform: translate(-50%,-50%); /*自己的50% */
}
方案四:
css不定宽高水平垂直居中
.box{ height:600px;
display:flex;
justify-content:center;
align-items:center;
/* aa只要三句话就可以实现不定宽高水平垂直居中。 */
}
.box>div{
background: green;
width: 200px;
height: 200px;
}
方案五:
将父盒子设置为table-cell元素,可以使用text-align:center和vertical-align:middle实现水平、垂直居中。比较完美的解决方案是利用三层结构模拟父子结构
<p class="outerBox tableCell">
</p><p class="ok">
</p><p class="innerBox">tableCell</p>
<p></p>
<p></p> /*
table-cell实现居中
将父盒子设置为table-cell元素,设置
text-align:center,vertical-align: middle;
子盒子设置为inline-block元素
*/
.tableCell{
display: table;
}
.tableCell .ok{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.tableCell .innerBox{
display: inline-block;
}
方案六:
对子盒子实现绝对定位,利用calc计算位置
<p class="outerBox calc">
</p><p class="innerBox">calc</p>
<p></p> /*绝对定位,clac计算位置*/
.calc{
position: relative;
}
.calc .innerBox{
position: absolute;
left:-webkit-calc((500px - 200px)/2);
top:-webkit-calc((120px - 50px)/2);
left:-moz-calc((500px - 200px)/2);
top:-moz-calc((120px - 50px)/2);
left:calc((500px - 200px)/2);
top:calc((120px - 50px)/2);
}
最新文章
- Nodejs安装
- Format
- DDD领域驱动设计之领域服务
- SQLite剖析之事务处理技术
- 【转】Android中的事件分发和处理
- Mina、Netty、Twisted一起学(五):整合protobuf
- iOS高效开发之Xcode应用插件
- GoF23种设计模式
- 完成Adventure中的主方法
- javascript中===与==
- Curl上传文件
- ACM——线性表操作
- python包管理-distutils,setuptools,pip,virtualenv等介绍
- confluence的权限管理
- 怎样在Github参与一个开源项目
- xml数据传输
- 什么是IPFS?(一)
- 爬虫值requests库
- netcore开发windows普通服务(非Web)并一键发布到服务器
- 浅谈Java线程安全
热门文章
- C#程序员应该养成的程序性能优化写法
- 程序员 各种PDF格式电子书--免费网盘资源
- Java面向对象 包
- 百度SMS SDK for .Net
- DevOps之负载均衡
- Android Annotations Eclipse 配置 (3)
- ios 指定页面禁用第三方键盘,使用系统的键盘
- 解题笔记-洛谷-P1010 幂次方
- Ubuntu安装Flash视频插件
- Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required