水平垂直居中的六种方法
2023-02-25 18:20:28 时间
方法一:
绝对定位方法:不确定当前div的宽度和高度,采用 transform: translate(-50%,-50%); 当前div的父级添加相对定位(position: relative;)
图片展示:
代码如下:
div{
background:red;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%, -50%);
}
方法二:
绝对定位方法:确定了当前div的宽度,margin值为当前div宽度一半的负值
图片展示: 如方法一的图片展示
代码如下:
div{
width:600px;
height: 600px;
background:red;
position: absolute;
left:50%;
top:50%;
margin-left:-300px;
margin-top:-300px;
}
方法三:
绝对定位方法:绝对定位下top left right bottom 都设置0
图片展示: 如方法一的图片展示
代码如下:
<!--html-->
<div class="child">我是子级</div>
/**css**/
div.child{
width: 600px;
height: 600px;
background: red;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
方法四:
flex布局方法:当前div的父级添加flex css样式
展示图如下:
代码如下:
<!--html-->
<div class="box">
<div class="child">child</div>
</div>
/**css**/
.box{
height:800px;
-webkit-display:flex;
display:flex;
-webkit-align-items:center;
align-items:center;
-webkit-justify-content:center;
justify-content:center;
border:1px solid #ccc;
}
div.child{
width:600px;
height:600px;
background-color:red;
}
方法五:
table-cell实现水平垂直居中: table-cell middle center组合使用
展示图如下:
代码如下:
<!--html-->
<div class="table-cell">
<p>我爱你</p>
</div>
/**css**/
.table-cell {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
border:1px solid #666;
}
方法六:
绝对定位:calc() 函数动态计算实现水平垂直居中
代码如下:
<!--html-->
<div class="calc">
<div class="child">calc</div>
</div>
/**css**/
.calc{
position: relative;<br> border: 1px solid #ccc;<br> width: 400px;<br> height: 160px;
}
.calc .child{
position: absolute;<br> width: 200px;<br> height: 50px;
left:-webkit-calc((400px - 200px)/2);
top:-webkit-calc((160px - 50px)/2);
left:-moz-calc((400px - 200px)/2);
top:-moz-calc((160px - 50px)/2);
left:calc((400px - 200px)/2);
top:calc((160px - 50px)/2);
}
相关文章
- Jgit的使用笔记
- 利用Github Action实现Tornadofx/JavaFx打包
- 叹息!GitHub Trending 即将成为历史!
- 微软软了?开源社区讨论炸锅,GitHub CEO 亲自来答
- GitHub Trending 列表频现重复项,前后端都没去重?
- Photoshop Elements 2021版本软件安装教程(mac+windows全版本都有)
- (ps全版本)Photoshop 2020的安装与破解教程(mac+windows全版本都有)
- (ps全版本)Photoshop cc2018的安装与破解教程(mac+windows全版本,包括2023
- 环境搭建:Oracle GoldenGate 大数据迁移到 Redshift/Flat file/Flume/Kafka测试流程
- 每个开发人员都要掌握的:最小 Linux 基础课
- 来撸羊毛了!Windows 环境下 Hexo 博客搭建,并部署到 GitHub Pages
- 超实用!手把手入门 MongoDB:这些坑点请一定远离
- 【GitHub日报】22-10-09 zustand、neovim、webtorrent、express 等4款App今日上新
- 【GitHub日报】22-10-10 brew、minio、vite、seaweedfs、dbeaver 等8款App今日上新
- 【GitHub日报】22-10-11 cobra、grafana、vue、ToolJet、redwood 等13款App今日上新
- Photoshop 2018 下载及安装教程(mac+windows全版本都有,包括最新的2023)
- Photoshop 2017 下载及安装教程(mac+windows全版本都有,包括最新的2023)
- Photoshop 2020 下载及安装教程(mac+windows全版本都有,包括最新的2023)
- Photoshop 2023 资源免费下载(mac+windows全版本都有,包括最新的2023)
- 最新版本Photoshop CC2018软件安装教程(mac+windows全版本都有,包括2023