<div class="wrap">
<div class="inner"></div>
</div>
複製程式碼
1. absolute+transform實現
style程式碼
<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以上支援
2. absolute+margin實現
style程式碼
<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%是相對於自身的寬度。
3.absolute+margin:auto實現
<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>
複製程式碼
3.flex+margin:auto實現
<style>
.wrap {
border: 1px solid palevioletred;
height: 200px;
width: 200px;
display: flex;
}
.inner {
border: 1px solid palevioletred;
width: 50%;
height: 50%;
margin: auto;
}
</style>
複製程式碼
4.flex實現
<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>
複製程式碼