1. 作用概述
居中定位元素是网页设计中的常见需求,通常用于模态框、提示框、图像等元素。通过不同的 CSS 技巧,可以实现水平和垂直居中。
2. 使用方法
2.1 使用 transform 和绝对定位
.centered-element {
position: absolute; /* 或 fixed */
top: 50%; /* 将顶部位置设置为父元素的 50% */
left: 50%; /* 将左侧位置设置为父元素的 50% */
transform: translate(-50%, -50%); /* 将元素的中心点移动到父元素的中心点 */
}
说明
-
position: absolute; 或 position: fixed; 使元素相对于其最近的定位祖先元素(position不是static)进行定位。
-
top: 50%; 和 left: 50%; 将元素的左上角定位到父元素的中心(该元素的上面距离父元素的距离是父元素的50%,左边距离父元素的距离有父元素的50%,)。
-
transform: translate(-50%, -50%); 将元素的中心点移动到父元素的中心,从而实现居中效果(将元素向左(负数就是向左)移动自身元素的宽度50%,向上(负数就是向上)移动自身元素的宽度50%)。
2.2 使用 Flex
.flex-parent {
/* 父元素设置 */
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
/* 演示用样式 */
width: 300px;
height: 300px;
background: #f0f0f0;
}
.flex-child {
/* 演示用样式 */
padding: 20px;
background: #6495ED;
color: white;
}
2.3 使用Grid
.grid-parent { /* 父元素设置 */
display: grid;
place-items: center; /* 简写方式 */
/* 或者分开写: align-items: center; justify-items: center; */
/* 演示用样式 */
width: 300px;
height: 300px;
background: #f0f0f0;
}
.grid-child { /* 演示用样式 */
padding: 20px;
background: #6495ED;
color: white;
}
2.3 使用position和margin
.margin-parent {
/* 父元素设置 */
position: relative;
/* 演示用样式 */
width: 300px;
height: 300px;
background: #f0f0f0;
}
.margin-child {
/* 核心居中代码,“父相子绝” */
position: absolute; /*绝对定位会和最近的有定位(有position属性即可)的父元素相对定位,6行语句缺一不可*/
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
/* 必须设置宽高 */
width: 100px;
height: 100px;
/* 演示用样式 */
background: #6495ED;
color: white;
text-align: center; /*让文字水平居中*/
line-height: 100px; /*让文字垂直居中,一般与盒子高度相同即可居中*/
}