码迷,mamicode.com
首页 > Web开发 > 详细

css 水平居中,垂直居中

时间:2020-04-21 12:52:51      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:position   sla   flex   idt   line   需要   table   tran   red   

<div class="box">
<img src="./1.jpg" />
</div>

第一种:水平居中

.box {
width:300px;
height:300px;
border:2px solid red;
}
img{
display:block;
width:100px;
height:100px;
margin:0 auto;
}

第二种:水平居中

.box{
width:300px;
height:300px;
border:2px solid red;
text-align:center;
}
img{
width:100px;
height:100px;
display:inline-block;
}

第三种:水平垂直居中 定位+需要居中元素的margin减去宽高的一半(取负值)

.box {
width:300px;
height:200px;
border:1px solid red;
position:relative;
}
img{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
}

第四种:水平垂直居中 定位+margin:auto

.box{
width:300px;
height:200px;
border:1px solid red;
position:relative;
}
img{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:0 auto;
}

第五种:水平垂直居中  定位+transform

.box {
width:300px;
height:200px;
position:relative;
border:1px solid red;
}
img{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}

第六种:水平垂直居中 display:table-cell

.box{
width:300px;
height:200px;
border:2px solid red;
display:table-cell;
verticall-align:middle;
text-align:center;
}
img{
width:100px;
height:100px;
}
.box-table{
display:table
}
<div class="box-table">
<div class="box">
<img src="./1.jpg" />
</div>
</div>

第七种:垂直水平居中 flex

.box{
width:300px;
height:200px;
border:1px solid red;
display:flex;
justify-content:center;
align-items:center;
}
img{
width:100px;
height:100px;
}

 

css 水平居中,垂直居中

标签:position   sla   flex   idt   line   需要   table   tran   red   

原文地址:https://www.cnblogs.com/sunnyeve/p/12743576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!