让div水平垂直居中的六种方法
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
方法一:绝对定位方法:不确定当前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<div class="child">我是子级</div>1 div{
width:600px;
height:600px;
background:red;
position:absolute;
left:0;
top:0;
bottom:0;
right:0;
margin:auto;
}方法四: flex布局方法:当前div的父级添加flex css样式<div class="box"> <div class="child">child</div> </div> .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:red;
}方法五:table-cell实现水平垂直居中: table-cell middle center组合使用(让div里面的文本内容)<div class="table-cell"> <p>我爱你</p> </div> .table-cell{
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
border: 1px solid #666;
}方法六:绝对定位:calc() 函数动态计算实现水平垂直居中<div class="calc"> <div class="child">calc</div> </div> .calc{
position: relative;
border: 1px solid #ccc;
width: 400px;
height: 160px;
}
.calc .child{
position: absolute;
width: 200px;
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);
}
该文章在 2023/12/1 15:45:57 编辑过 |
关键字查询
相关文章
正在查询... |