掌握元素定位和层叠上下文
元素按照正常的文档流排列,不受 top, right, bottom, left 的影响。
元素相对于其正常位置进行定位,不会脱离文档流。
元素相对于最近的已定位祖先元素进行定位,会脱离文档流。
元素相对于视口进行定位,不会随页面滚动而移动。
元素在滚动到一定位置时会固定,结合了 relative 和 fixed 的特性。
.static {
position: static;
}
.relative {
position: relative;
top: 20px;
left: 20px;
}
.absolute {
position: absolute;
top: 50px;
right: 50px;
}
.sticky {
position: sticky;
top: 0;
}z-index 属性用于控制元素的堆叠顺序,值越大,元素越在上面。
.element1 {
position: absolute;
z-index: 1;
}
.element2 {
position: absolute;
z-index: 2; /* 在上面 */
}.transform-item {
transition: transform 0.3s ease;
}
.transform-item:hover {
transform: scale(1.2) rotate(10deg);
}.transforms {
/* 位移 */
transform: translate(10px, 20px);
transform: translateX(10px);
transform: translateY(20px);
/* 缩放 */
transform: scale(1.2);
transform: scaleX(1.5);
transform: scaleY(0.8);
/* 旋转 */
transform: rotate(45deg);
/* 倾斜 */
transform: skew(10deg, 5deg);
transform: skewX(10deg);
transform: skewY(5deg);
/* 组合变换 */
transform: translate(10px, 10px) rotate(45deg) scale(1.2);
}.perspective {
perspective: 1000px;
}
.transform-3d {
transform: rotate3d(1, 1, 0, 45deg);
transform-style: preserve-3d;
}.navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
z-index: 1000;
}
.content {
margin-top: 60px; /* 为固定导航栏留出空间 */
}.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 8px;
max-width: 500px;
width: 90%;
}.tooltip {
position: relative;
cursor: help;
}
.tooltip::after {
content: "提示文本";
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background: #333;
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 14px;
opacity: 0;
transition: opacity 0.3s;
pointer-events: none;
}
.tooltip:hover::after {
opacity: 1;
}