垂直水平居中的6中不同方法

页面中垂直水平居中的几种方法:

页面效果:

公共样式:

box{
border: 1px solid red;
width: 400px;
height: 400px;
}
.con{
background: lightpink;
width: 200px;
height: 200px;
}

方法一:absolute + 负margin 

css:

.box{
position: relative;
}
.con{
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}

html:

方法二:absolute + margin auto 

css:

.box{
position: relative;
}
.con{
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}

html:

方法三:absolute + transform

css:

.box{
position: relative;
}
.con{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);

}

html:

方法四:lineheight

css:

.box{
line-height: 400px;
text-align: center;
}
.con{
font-size: 18px;
display: inline-block;
vertical-align: middle;
text-align: center;
line-height: 200px;
}

html:

方法五:css-table 

css:

.box{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.con{
display: inline-block;
}

html:

方法六:flex

css:

.box{
display: flex;
justify-content: center;
align-items: center;
}

html:

猜你喜欢

转载自www.cnblogs.com/w-yue/p/11772086.html