方式一:
直接根據高度和寬度配置,簡單粗暴
.pdiv{
width: 500px;
height: 400px;
margin: 100px auto;
border: 1px solid green;
position: relative;
}
.div{
width: 300px;
height: 100px;
line-height: 100px;
text-align: center;
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -150px;
}
方式二:
依據瀏覽器窗口進行絕對定位:fixed,CSS3
.pdiv{ width: 500px; height: 400px; margin: 100px auto; border: 1px solid green; text-align: center; position: relative; } .div{ margin: auto; width: 300px; height: 100px; line-height: 100px; text-align: center; border: 1px solid red; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
方式三:
flex盒子模型
.pdiv{
width: 500px;
height: 400px;
margin: 100px auto;
border: 1px solid green;
display: flex;
align-content: center;
justify-content: center;
}
.div{
margin: auto;
width: 300px;
height: 100px;
line-height: 100px;
text-align: center;
border: 1px solid red;
}
方式四:
絕對佈局
.pdiv{
width: 500px;
height: 400px;
margin: 100px auto;
border: 1px solid green;
text-align:center;
position: relative;
}
.div{
width: 300px;
height: 100px;
line-height: 100px;
text-align: center;
border: 1px solid red;
position: absolute;
top:0;left: 0;
right: 0; bottom: 0;
margin: auto;
}
方式五:
使用JS調整,在此不再闡述,可自行學習