padding

padding CSS 简写属性一次性设置元素所有四条边的内边距区域

尝试一下

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

备注: 内边距创建元素内部的额外空间。相反,margin 创建元素外部的额外空间。

属性构成

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

语法

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

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

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

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

/* 全局值 */
padding: inherit;
padding: initial;
padding: revert;
padding: revert-layer;
padding: unset;

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

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

取值

<length>

作为定值的内边距尺寸。必须是非负值。

<percentage>

相对于包含块的行内尺寸(水平语言中的宽度,由 writing-mode 定义)的百分比。必须是非负值。

形式定义

初始值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}

<padding-top> =
<length-percentage [0,∞]>

<length-percentage> =
<length> |
<percentage>

示例

以像素为单位设置内边距

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

参见