1.position和transform结合
position设置为absolute,top和left分别设置为50%;
再利用translate,translate-x,translate-y分别设置为-50%;
div{
width: 50%;
height: 50%;
position: absolute;
transform: translate(-50% -50%);
}
2.position和 margin结合
position 设置为absolute,top,left,right,bottom都设置为0,
margin设为auto
div{
width: 50%;
height: 50%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
3.flex布局
外层div设置为display:flex,justify-content:center;(水平居中),align-items:center(垂直居中)
<div id="wrapper">
<div id="content"></div>
</div>
// css
<style>
#wrapper{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#content{
width: 50%;
heigth: 50%;
background-color: red;
}
</style>
4.postion:absolute 和vw,vh结合
<div id="wrapper">
<div id="content"></div>
</div>
<style>
#wrapper{
width: 100vw;
height: 100vh;
position: relative;
background-color: blue;
}
#content{
background-color: yellow;
width: 50vw;
height: 50vh;
position: absolute;
top: 25vh;
left: 25vw;
}
</style>
5.table布局
wraper: display: table
content: display: table-cell;text-align: center;vertical-align: center;
<style>
#wrapper{
width: 100%;
height: 100%;
display: table;
}
#content{
width: 50%;
height: 50%;
display: table-cell;
vertical-align: center;
text-align: center;
}
</style>
6.当div的宽高固定时,可以利用position和负边距
position: absolute,top,left分别为50%;
margin-top,margin-left分别为自身高度,自身宽度的一半的负值
<style>
div{
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-bottom: -100px;
}
</style>
网友评论