引言
今天来聊聊CSS中一个超级实用的功能------定位布局。废话不多说,直接进入正题!
基础篇------定位类型
CSS中有5种定位方式,但最常用的就3种:static
、relative
和absolute
。还有两个特殊成员:fixed
和sticky
。
1. 静态定位(static)
这是默认值,元素按照正常文档流排列。
css
.box {
position: static; /* 可以省略不写 */
}
注意:设置了static
定位的元素,top
、right
、bottom
、left
和z-index
属性都无效!
2. 相对定位(relative)
元素先放在正常位置,然后相对于自己原来的位置进行偏移。
css
.box {
position: relative;
top: 20px;
left: 30px;
}
看个实际例子:
html
<div class="box">我是相对定位的盒子</div>
<div>我是普通盒子</div>
css
.box {
position: relative;
top: 20px;
left: 30px;
background: pink;
}
效果:粉色的盒子会向下移动20px,向右移动30px,但原来的位置仍然保留着,不会影响其他元素。
3. 绝对定位(absolute)
元素脱离文档流,相对于最近的已定位祖先元素(非static)定位。
css
.box {
position: absolute;
top: 0;
right: 0;
}
看个案例:
html
<div class="parent">
<div class="child">我是绝对定位的子元素</div>
</div>
css
.parent {
position: relative; /* 关键! */
width: 300px;
height: 200px;
border: 1px solid #ccc;
}
.child {
position: absolute;
bottom: 10px;
right: 10px;
background: lightblue;
}
效果:浅蓝色的子元素会定位在父元素的右下角,距离底部和右边各10px。
4. 固定定位(fixed)
元素相对于视口定位,滚动页面时位置不变。
css
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: white;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
5. 粘性定位(sticky)
元素在滚动到特定位置时变成固定定位。
css
.nav {
position: sticky;
top: 0;
background: white;
}
进阶篇------定位实战
案例一:模态框
html
<div class="modal">
<div class="modal-content">
<h2>我是模态框</h2>
<p>点击外部区域关闭</p>
</div>
</div>
css
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 5px;
width: 80%;
max-width: 500px;
}
案例二:悬浮按钮
html
<button class="float-btn">+</button>
css
.float-btn {
position: fixed;
bottom: 30px;
right: 30px;
width: 60px;
height: 60px;
border-radius: 50%;
background: #2196F3;
color: white;
font-size: 24px;
border: none;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
cursor: pointer;
}
案例三:粘性导航栏
html
<header class="sticky-header">
<nav>
<a href="#">首页</a>
<a href="#">产品</a>
<a href="#">关于</a>
</nav>
</header>
<div class="content">
<!-- 很多内容 -->
</div>
css
.sticky-header {
position: sticky;
top: 0;
background: white;
padding: 15px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
常见问题
1. 绝对定位的元素宽度问题
绝对定位的元素默认宽度是内容宽度,不是100%父元素宽度。如果需要撑满父元素:
css
.box {
position: absolute;
left: 0;
right: 0; /* 这样宽度就是100%了 */
}
2. z-index堆叠问题
定位元素可以使用z-index
控制堆叠顺序,但要注意:
- 只对定位元素(非static)有效
- 父元素的
z-index
会影响子元素
3. 绝对定位的居中技巧
css
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
总结
static
:默认值,不定位relative
:相对自身定位,不脱离文档流absolute
:相对于最近定位祖先定位,脱离文档流fixed
:相对于视口定位,脱离文档流sticky
:滚动到阈值时变为固定定位
记住这些,你的页面布局能力就能提升一大截!