CSS Padding

Keywords

css, padding, css padding, dataidea, data science, web development, website

Photo by DATAIDEA

CSS Padding

CSS Padding creates space within an element

It clears an area around the inside of an element.

CSS Padding - Individual Sides

The following properties set the length of the padding on each side

  • padding-top: sets the padding area on top of an element
  • padding-right: sets the padding area on the right of an element
  • padding-bottom: sets the padding area on the bottom of an element
  • padding-left: sets the padding area on the left of an element

Valid values:

  • <length>
  • <percentage>

Example:

Here is an example of different padding lenghts on each side.

div {
    padding-top: 30px;
    padding-right: 50px;
    padding-bottom: 70px;
    padding-left: 90px;
    background: lightgrey;
    border: 1px solid red; 
}

Output:

Here is an example of different padding lenghts on each side.

CSS Padding - Shorthand Property

The padding CSS property is a shorthand for the following properties:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

The padding CSS property can have one, two, three, or four values.

  • When one value is specified, it applies the same padding to all four sides
  • When two values are specified, the first value applies to the top and bottom, the second value applies to the left and right
  • When three values are specified, the first value applies to the top, the second to the left and right and the third to the bottom
  • When four values are specified, the paddings apply to the top, right, bottom and left in that order (clockwise) respectively.

Padding and Width

The CSS width property only specifies the width of an element’s content area. It does not include padding, borders and margins.

Therefore if an element has a specified width and padding, they will be added together.

Example:

div {
    width: 200px;
    padding: 10px;
    /* the actual rendered width */
    /* is now 220px */
    background: blue;
    height: 100px; 
}

Output:

Padding and Height

The CSS height property only specifies the height of an element’s content area. It does not include padding, borders and margins

Therefore if an element has a specified height and padding, they will be added together.

Example:

div {
    height: 200px;
    padding: 10px;
    /* the actual rendered height */
    /* is now 220px */
    background: blue;
    width: 100px;
}

Output:

To keep the height at 200px we need to set the box-sizing to border-box.

Increasing the padding will now decrease the content space inside the element

Example:

div {
    height: 200px;
    padding: 10px;
    /* the actual rendered */
    /* height is still 200px */
    background: blue;
    width: 100px;
}

Output:

To be among the first to hear about future updates of the course materials, simply enter your email below, follow us on (formally Twitter), or subscribe to our YouTube channel.

Back to top