Skip to content
On this page

CSS 布局方式

CSS 提供了多种布局方式来控制网页元素的排列和定位。

概述

CSS 布局是指控制网页元素的位置、大小和排列方式的技术。

传统布局方式

普通文档流

元素按照默认的文档顺序排列:

css
.normal-flow {
  display: block; /* 块级元素 */
  display: inline; /* 行内元素 */
  display: inline-block; /* 行内块元素 */
}

浮动布局

使用 float 属性使元素脱离正常文档流:

css
.float-element {
  float: left;
  width: 50%;
}

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

定位布局

使用 position 属性精确定位元素:

css
.positioned {
  position: relative; /* 相对定位 */
  position: absolute; /* 绝对定位 */
  position: fixed; /* 固定定位 */
  position: sticky; /* 粘性定位 */
}

现代布局方式

Flexbox 布局

弹性盒子布局,适合一维布局:

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

.flex-item {
  flex: 1; /* 等价于 flex: 1 1 0% */
}

Grid 布局

网格布局,适合二维布局:

css
.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}

.grid-item {
  grid-column: span 2; /* 跨越2列 */
}

显示属性

display 属性值

css
.block { display: block; }
.inline { display: inline; }
.inline-block { display: inline-block; }
.none { display: none; }
.flex { display: flex; }
.grid { display: grid; }
.table { display: table; }

容器查询 (Container Queries)

新的响应式设计方法:

css
.card-container {
  container-type: inline-size;
}

@container (min-width: 400px) {
  .card {
    display: flex;
  }
}

层叠上下文

控制元素的堆叠顺序:

css
.stacking-context {
  position: relative;
  z-index: 10;
  /* 或使用其他创建层叠上下文的属性 */
  opacity: 0.9;
  transform: translateZ(0);
}

响应式布局

使用媒体查询实现响应式设计:

css
.responsive-layout {
  display: block;
}

@media (min-width: 768px) {
  .responsive-layout {
    display: flex;
  }
}

最佳实践

  • 根据布局需求选择合适的布局方式
  • 优先使用现代布局方式(Flexbox、Grid)
  • 理解不同布局方式的适用场景
  • 考虑可访问性和响应式设计