text-align: center:作用於父元素,置中行內/行內區塊子元素margin: 0 auto:作用於子元素(需為區塊元素),置中區塊本身前提:子元素未被 float 影響。
line-height = 父元素 height → 文字垂直置中。僅適用單行文字,margin: auto 0 無效。
.parent { position: relative; width: 300px; height: 200px; }
.child {
position: absolute;
top: 50%; left: 50%;
width: 100px; height: 80px; /* 必須知寬高 */
margin-left: -50px; /* 負一半寬度 */
margin-top: -40px; /* 負一半高度 */
}
此法為前端工程師居家旅行必備絕招。