<div class="father"><div class="child"></div>
</div>
1. Flex(推荐)
.father{width: 300px;height: 300px;background-color: red;display: flex; /* flex 方法 */justify-content: center; /* flex 方法 */align-items: center; /* flex 方法 */
}
.child{width: 100px;height: 100px;background-color: blue;
}
2. Grid(推荐)
.father{width: 300px;height: 300px;background-color: red;display: grid; /* flex 方法 */place-items: center; /* flex 方法 */
}
.child{width: 100px;height: 100px;background-color: blue;
}
3. 绝对定位 + Transform
.father{width: 300px;height: 300px;background-color: red;position: relative; /* 绝对定位 + Transform */
}
.child{width: 100px;height: 100px;background-color: blue;position: absolute; /* 绝对定位 + Transform */top: 50%; /* 绝对定位 + Transform */left: 50%; /* 绝对定位 + Transform */transform: translate(-50%,-50%); /* 绝对定位 + Transform */
}
4. Margin Auto(需已知尺寸)
.father{width: 300px;height: 300px;background-color: red;position: relative; /* Margin Auto */
}
.child{width: 100px;height: 100px;background-color: blue;position: absolute; /* Margin Auto */top: 0; /* Margin Auto */left: 0; /* Margin Auto */right: 0; /* Margin Auto */bottom: 0; /* Margin Auto */margin: auto; /* Margin Auto */
}
5. 行高方法(适用于单行文本)
.father {width: 300px; /* 行高方法 */ height: 300px; /* 行高方法 */ background-color: #f0f8f8;
}
.child {line-height: 300px; /* 行高方法 */ text-align: center; /* 行高方法 */ color: #2f4f4f;
}