浮动与定位
浮动(float)和定位(position)是传统布局的两大工具。虽然现代布局多用 Flex/Grid,但理解它们仍然重要。
浮动 float
float: left/right 让元素向左或向右浮动,常用于图文混排。浮动元素会脱离文档流,父容器可能塌陷,需要清除浮动(clearfix 或 overflow: hidden)。
定位 position
relative:相对自身原位置偏移,不脱离文档流;absolute:相对最近的已定位祖先定位,脱离文档流;fixed:相对视口固定,滚动不动(如返回顶部按钮);sticky:粘性定位,滚动到阈值后固定。
z-index 控制层叠顺序,值大的在上层。只有定位元素(relative/absolute/fixed/sticky)才受 z-index 影响。
代码示例
<style>
.wrap { position: relative; padding: 20px; background: #f8f9fa; }
.float-img { float: left; margin-right: 12px; }
.clearfix::after { content: ""; display: block; clear: both; }
.badge {
position: absolute; /* 相对 .wrap 定位 */
top: -8px; right: 16px;
background: #ff4757; color: #fff;
padding: 2px 10px; border-radius: 10px;
font-size: 12px;
}
.back-top {
position: fixed; /* 固定在视口 */
right: 20px; bottom: 20px;
background: #3b5bdb; color: #fff;
padding: 8px 12px; border-radius: 8px;
cursor: pointer;
}
</style>
<div class="wrap">
<span class="badge">NEW</span>
<img class="float-img" src="https://picsum.photos/100/80" alt="示例图">
<p class="clearfix">文字环绕图片排版的经典效果,通过 float 实现。</p>
</div>
<div class="back-top">回到顶部</div>
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
color: #333; | 文字颜色 |
background: #fff; | 背景色 / 背景图 |
font-size: 16px; | 字号 |
font-family: Arial; | 字体 |
font-weight: bold; | 字重(加粗) |
margin: 10px; | 外边距(上右下左) |
padding: 10px; | 内边距 |
border: 1px solid #ccc; | 边框:粗细 样式 颜色 |
border-radius: 8px; | 圆角 |
width: 100%; | 宽度 |
height: 200px; | 高度 |
display: flex; | 弹性布局(现代布局主力) |
display: none; | 隐藏元素 |
position: relative / absolute / fixed; | 定位方式 |
top / left / right / bottom | 定位偏移 |
text-align: center; | 文字水平对齐 |
line-height: 1.6; | 行高 |
overflow: hidden; | 内容溢出处理 |
box-shadow: 0 2px 8px rgba(0,0,0,.1); | 阴影 |
transition: all .3s; | 过渡动画 |
cursor: pointer; | 鼠标手型 |
z-index: 10; | 层叠顺序 |
max-width: 1200px; margin: 0 auto; | 容器居中(经典写法) |
@media (max-width: 768px) {} | 响应式断点 |
:hover | 鼠标悬停状态 |