<div class="wrap">
<div class="inner"></div>
</div>
複製代碼
style代碼html
<style>
.wrap {
border: 1px solid palevioletred;
height: 200px;
width: 200px;
position: relative;
}
.inner {
border: 1px solid palevioletred;
width: 50%;
height: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
複製代碼
left:50%中的百分比是相對於定位父級的寬度。
translate:50%是相對於自身的寬度。
缺點:ie9以上支持flex
style代碼spa
<style>
.wrap {
border: 1px solid palevioletred;
height: 200px;
width: 200px;
position: relative;
}
.inner {
border: 1px solid palevioletred;
width: 50%;
height: 50%;
position: absolute;
top: 50%;
left: 50%;
margin-left: -25%;
margin-top: -25%;
}
</style>
複製代碼
left:50%中的百分比是相對於定位父級的寬度。
margin:50%是相對於自身的寬度。
3d
<style>
.wrap {
border: 1px solid palevioletred;
height: 200px;
width: 200px;
position: relative;
}
.inner {
border: 1px solid palevioletred;
width: 50%;
height: 50%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
複製代碼
<style>
.wrap {
border: 1px solid palevioletred;
height: 200px;
width: 200px;
display: flex;
}
.inner {
border: 1px solid palevioletred;
width: 50%;
height: 50%;
margin: auto;
}
</style>
複製代碼
<style>
.wrap {
border: 1px solid palevioletred;
height: 200px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.inner {
border: 1px solid palevioletred;
width: 50%;
height: 50%;
}
</style>
複製代碼