改变页面布局的 CSS 属性

常见的 CSS 布局属性及其作用

问题

列出你所知道可以改变页面布局的属性。

解答

1. display

控制元素的显示类型,是最基础的布局属性。

.element {
  display: block;       /* 块级元素 */
  display: inline;      /* 行内元素 */
  display: inline-block;/* 行内块元素 */
  display: flex;        /* 弹性布局 */
  display: grid;        /* 网格布局 */
  display: none;        /* 隐藏元素,不占空间 */
}

2. position

控制元素的定位方式。

.element {
  position: static;    /* 默认,正常文档流 */
  position: relative;  /* 相对定位,相对自身偏移 */
  position: absolute;  /* 绝对定位,脱离文档流 */
  position: fixed;     /* 固定定位,相对视口 */
  position: sticky;    /* 粘性定位,滚动时固定 */
}

3. float 和 clear

浮动布局,元素脱离文档流向左或向右浮动。

.float-left {
  float: left;
}

.float-right {
  float: right;
}

/* 清除浮动 */
.clearfix::after {
  content: '';
  display: block;
  clear: both;
}

4. Flexbox 相关属性

.container {
  display: flex;
  flex-direction: row;        /* 主轴方向 */
  flex-wrap: wrap;            /* 换行 */
  justify-content: center;    /* 主轴对齐 */
  align-items: center;        /* 交叉轴对齐 */
  gap: 10px;                  /* 间距 */
}

.item {
  flex: 1;                    /* 弹性比例 */
  flex-grow: 1;               /* 放大比例 */
  flex-shrink: 0;             /* 缩小比例 */
  flex-basis: 100px;          /* 初始大小 */
  order: 1;                   /* 排列顺序 */
  align-self: flex-start;     /* 单独对齐 */
}

5. Grid 相关属性

.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;  /* 列定义 */
  grid-template-rows: 100px auto;      /* 行定义 */
  grid-gap: 20px;                      /* 间距 */
  grid-template-areas:                 /* 区域布局 */
    "header header"
    "sidebar main";
}

.item {
  grid-column: 1 / 3;         /* 跨列 */
  grid-row: 1 / 2;            /* 跨行 */
  grid-area: header;          /* 指定区域 */
}

6. 盒模型属性

.element {
  width: 200px;
  height: 100px;
  margin: 10px;               /* 外边距,影响元素间距 */
  padding: 20px;              /* 内边距,影响内容区域 */
  box-sizing: border-box;     /* 盒模型计算方式 */
}

7. overflow

控制内容溢出时的表现。

.element {
  overflow: visible;   /* 默认,溢出可见 */
  overflow: hidden;    /* 隐藏溢出,可创建 BFC */
  overflow: scroll;    /* 始终显示滚动条 */
  overflow: auto;      /* 需要时显示滚动条 */
}

8. 多列布局

.element {
  columns: 3;                  /* 列数 */
  column-width: 200px;         /* 列宽 */
  column-gap: 20px;            /* 列间距 */
  column-rule: 1px solid #ccc; /* 列分隔线 */
}

9. 其他布局相关属性

.element {
  z-index: 10;          /* 层叠顺序,需配合 position */
  visibility: hidden;   /* 隐藏但保留空间 */
  vertical-align: middle; /* 行内元素垂直对齐 */
  table-layout: fixed;  /* 表格布局算法 */
}

关键点

  • display 是最基础的布局属性,决定元素的显示类型和布局模式
  • position 配合 top/right/bottom/left 实现定位,absolute 和 dbpnk 会脱离文档流
  • float 是传统布局方式,现代开发中已被 Flexbox 和 Grid 取代
  • Flexbox 适合一维布局(行或列),Grid 适合二维布局(行和列同时控制)
  • box-sizing: border-box 让宽高计算更直观,是现代 CSS 的标配