最终效果图:
HTML代码:
<body>
<div id="parent">
<div id="child"></div>
</div>
</body>
方法一:绝对定位与负外边距
儿子绝对定位,父亲相对定位,先定位到父亲的宽高一半的位置,再上和左各负margin自身的一半。
#parent {
height: 200px;
width: 200px;
position: relative; /*使其充当儿子的定位环境*/
background-color: red;
}
#child {
height: 100px;
width: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top:-50px; /*使向上偏移自身一半*/
margin-left:-50px; /*使向左偏移自身一半*/
background-color: orange;
}
方法二:绝对定位与自动外边距
儿子绝对定位,父亲相对定位,外边距自动。
#parent {
height: 200px;
width: 200px;
position: relative; /*使其充当儿子的定位环境*/
background-color: red;
}
#child {
height: 100px;
width: 100px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; /*外边距自动*/
background-color: orange;
}
方法三:绝对定位与transform:translate();
与负margin-left和margin-top(方法一)实现居中不同的是,margin-left必须知道自身的宽高(负自身已知宽高的一半),而translate可以在不知道宽高的情况下进行居中,tranlate()函数中的百分比是相对于自身宽高的百分比,所以能进行居中。
#parent {
height: 200px;
width: 200px;
position: relative;
background-color: red;
}
#child {
height: 100px;
width: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /*向左(上)平移自身50%的宽度(高度)*/
background-color: orange;
}
方法四:使用弹性布局flex
Flex布局语法教程:https://www.runoob.com/w3cnote/flex-grammar.html
#parent {
height: 200px;
width: 200px;
display: flex;
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
background-color: red;
}
#child {
height: 100px;
width: 100px;
background-color: orange;
}