padding

padding CSS 简写属性控制元素所有四条边的内边距区域

尝试一下

一个元素的内边距区域指的是其内容与其边框之间的空间。

备注: 内边距控制的是元素内部空出的空间。相反,margin 操作元素 外部空出的空间。

属性构成

该属性是以下属性的简写:

语法

css
/* 应用于所有边 */
padding: 1em;

/* 上边下边 | 左边右边 */
padding: 5% 10%;

/* 上边 | 左边右边 | 下边 */
padding: 1em 2em 2em;

/* 上边 | 右边 | 下边 | 左边 */
padding: 5px 1em 0 2em;

/* 全局值 */
padding: inherit;
padding: initial;
padding: unset;

padding 属性接受 1~4 个值。每个值可以是 <length><percentage>。取值不能为负。

  • 当只指定一个值时,该值会统一应用到全部四个边的内边距上。
  • 指定两个值时,第一个值会应用于上边和下边的内边距,第二个值应用于左边和右边
  • 指定三个值时,第一个值应用于上边,第二个值应用于右边和左边,第三个则应用于下边的内边距。
  • 指定四个值时,依次(顺时针方向)作为上边右边下边,和左边的内边距。

取值

<length>

以固定值为内边距。

<percentage>

相对于包含块宽度,以百分比值为内边距。

标准定义

初始值as each of the properties of the shorthand:
适用元素all elements, except table-row-group, table-header-group, table-footer-group, table-row, table-column-group and table-column. It also applies to ::first-letter and ::first-line.
是否是继承属性
Percentagesrefer to the width of the containing block
计算值as each of the properties of the shorthand:
  • padding-bottom: the percentage as specified or the absolute length
  • padding-left: the percentage as specified or the absolute length
  • padding-right: the percentage as specified or the absolute length
  • padding-top: the percentage as specified or the absolute length
Animation typea length

语法格式

padding = 
<'padding-top'>{1,4}

示例

以像素为单位设置内边距

HTML

html
<h4>此元素有合适的内边距。</h4>
<h3>此元素的内边距很大!</h3>

CSS

css
h4 {
  background-color: lime;
  padding: 20px 50px;
}

h3 {
  background-color: cyan;
  padding: 110px 50px 50px 110px;
}

结果

以像素和百分数为单位设置内边距

css
padding: 5%; /* 所有边:5% 的内边距 */

padding: 10px; /* 所有边:10px 的内边距 */

padding: 10px 20px; /* 上边和下边:10px 的内边距 */
/* 左边和右边:20px 的内边距 */

padding: 10px 3% 20px; /* 上边:10px 的内边距 */
/* 左边和右边:3% 的内边距 */
/* 下边:20px 的内边距 */

padding: 1em 3px 30px 5px; /* 上边:1em  的内边距*/
/* 右边:3px  的内边距*/
/* 下边:30px 的内边距*/
/* 左边:5px  的内边距*/

规范

Specification
CSS Box Model Module Level 3
# padding-shorthand

浏览器兼容性

BCD tables only load in the browser

参阅