Skip to content

CSS 布局

布局用于确定元素在页面中的位置与空间关系。现代前端中,FlexboxGrid 是主力方案。

1. 盒模型

每个元素都遵循盒模型:content + padding + border + margin

css
.box {
  width: 200px;
  padding: 20px;
  border: 2px solid #111;
  margin: 12px;
}

box-sizing

css
/* 默认:width 不含 padding 和 border */
box-sizing: content-box;

/* 推荐:width 包含 padding 和 border */
box-sizing: border-box;

项目中常见全局设置:

css
* {
  box-sizing: border-box;
}

2. display 基础

css
.element {
  display: block;
  display: inline;
  display: inline-block;
  display: none;
  display: flex;
  display: grid;
}
  • block:独占一行
  • inline:不换行,宽高通常不生效
  • inline-block:不换行且可设宽高
  • none:不参与布局
  • flex / grid:现代布局容器

3. position 定位

css
.element {
  position: static;
  position: relative;
  position: absolute;
  position: fixed;
  position: sticky;
}
  • relative:相对自身原位置偏移
  • absolute:相对最近的非 static 祖先定位
  • fixed:相对视口定位
  • sticky:在滚动阈值前后切换相对/固定效果
css
.floating {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 10;
}

4. 传统流式布局:float(了解)

css
.media-img {
  float: left;
  margin-right: 12px;
}

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

float 适合文字环绕,不建议作为页面主布局方案。

5. Flexbox(一维布局)

css
.container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.item {
  flex: 1 1 240px;
}

重点属性:

  • 容器:flex-directionjustify-contentalign-itemsflex-wrapgap
  • 项目:flexorderalign-self

6. Grid(二维布局)

css
.grid {
  display: grid;
  grid-template-columns: 240px 1fr 240px;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header header"
    "sidebar main aside"
    "footer footer footer";
  gap: 20px;
}

.main {
  grid-area: main;
}

重点属性:grid-template-columnsgrid-template-rowsgrid-areagap

7. 多列布局(文本类场景)

css
.article {
  column-count: 3;
  column-gap: 20px;
  column-rule: 1px solid #e5e7eb;
}

适合长文本,不适合复杂组件栅格。

8. 布局方案选择建议

  • 组件内部一维排列:优先 Flexbox
  • 页面级二维区域:优先 Grid
  • 文字环绕图片:可用 float
  • 叠层与悬浮元素:用 position + z-index

9. 示例:常见后台页面结构

css
.page {
  display: grid;
  grid-template-columns: 260px 1fr;
  min-height: 100vh;
}

.sidebar {
  border-right: 1px solid #e5e7eb;
}

.main {
  overflow: auto;
  padding: 24px;
}

Released under the MIT License.