center with "transform"
重點
.centered-element {
margin: 0;
/* ⭐️ child 跟隨 parent 的坐標系 */
position: absolute;
/* ⭐️ 垂直水平置中 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
程式碼
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
/* ⭐️ 1. parent 設定坐標系 */
position: relative;
height: 100vh;
border: 2px solid #006100;
background-color: orange;
}
.centered-element {
margin: 1em;;
padding: 1em;
border: 1px solid black;
background-color: rgba(255,255,255, 0.5);
/* ⭐️ 2. child 跟隨 parent 的坐標系 */
position: absolute;
/* ⭐️ 3. 垂直置中 */
top: 50%;
transform: translateY(-50%);
}
<div class="container">
<div class="centered-element">
<p>I'm a Camper, and I'm vertically centered. I'm a Camper, and I'm vertically centered. I'm a Camper, and I'm vertically centered. I'm a Camper, and I'm vertically centered. I'm a Camper, and I'm vertically centered. I'm a Camper, and I'm vertically centered.</p>
</div>
</div>
Last updated