?绝对定位方式 这种方式要求父级div的display属性不等于static,子元素大小必须确定
#parent {
width: 400px;
height: 400px;
background: yellow;
position: relative;
}
#child {
width: 200px;
height: 200px;
background: orange;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
?平移变换方式 和绝对定位方式原理一致,但因为平移距离可以用相当于自身的百分比来指定,因此子元素大小可以不确定
#parent {
width: 400px;
height: 400px;
background: yellow;
position: relative;
}
#child {
width: 200px;
height: 200px;
background: orange;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
?js定位方式 通过js来计算居中的位置并定位
#parent {
width: 400px;
height: 400px;
background: yellow;
position: absolute;
}
#child {
max-width: 80%;
width: auto;
height: auto;
}
$(() => {
$parent = $("#parent");
$child = $("#child");
$child.offset({
left: ($parent.width() - $child.width()) / 2,
top: ($parent.height() - $child.height()) / 2
});
});
?flex布局方式 flex布局可以设置子元素排列对齐方式
#parent {
width: 400px;
height: 400px;
background: yellow;
display: flex;
align-items: center;
justify-content: center;
}
#child {
width: 200px;
height: 200px;
background: orange;
}
?flex布局的另一种方式 flex布局自动将margin=auto的子元素处理为居中
#parent {
width: 400px;
height: 400px;
background: yellow;
display: flex;
}
#child {
width: 200px;
height: 200px;
background: orange;
margin: auto;
}
?grid布局方式 grid布局可以设置子元素的排列对齐方式
#parent {
width: 400px;
height: 400px;
background: yellow;
display: grid;
justify-items: center;
align-items: center;
}
#child {
width: 200px;
height: 200px;
background: orange;
}
?line-height方式 如果父div的内容只有单行文字,可以将line-height设置为和div等高,来让文字居中
Hello
#parent {
width: 400px;
height: 400px;
background: yellow;
text-align: center;
line-height: 400px;
}