在 CSS 中,定位是一项不可或缺的技术。常见的定位方式有以下几种:
position: static;
position: relative;
position: absolute;
position: fixed; 1. static 定位
默认是 static 定位,意味着元素在文档流中按照标准的顺序排列。top、left、right、bottom、z-index 的值都不会生效。
2. relative 定位
在 relative 定位中,元素在文档流中的位置不会改变,但它们的实际位置会在原来的位置上进行微调。可以使用 top、left、right、bottom 属性来控制元素的位置。
.box {
position: relative;
top: 5px;
left: 10px;
} 3. absolute 定位
在 absolute 定位中,元素会从文档流中完全脱离。它们的定位是相对于最近的一个非 static 定位的祖先元素。如果没有祖先元素,则相对于浏览器窗口进行定位。可以使用 top、left、right、bottom 属性来控制元素的位置。
.box {
position: absolute;
top: 50px;
left: 100px;
} 4. fixed 定位
与 absolute 定位相似,fixed 定位也会从文档流中脱离。区别在于,fixed 定位是相对于浏览器窗口进行定位。可以使用 top、left、right、bottom 属性来控制元素的位置。
.box {
position: fixed;
top: 0;
right: 0;
} 以上是 CSS 中常见的几种定位方式,灵活运用它们可以实现各种复杂布局。