Box Model

CSS Padding

Applying CSS Padding

CSS padding spaces content within elements, using shorthand syntax.

What is CSS Padding?

CSS padding is a crucial part of the box model that defines the space between the content of an element and its border. By adjusting padding, you can control the inner spacing of elements, improving the visual layout and readability of your web pages.

Padding vs. Margin

While both padding and margin are used to create space, they serve different purposes. Padding adds space inside an element, between the content and the element's border. Conversely, margin adds space outside an element, between the element's border and neighboring elements.

Syntax of CSS Padding

CSS padding can be specified using individual properties or a shorthand property. The individual properties are:

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

Alternatively, the padding shorthand allows you to specify all four padding sides in one property.

Single Value Padding

If you provide a single value to the padding property, it will apply the same padding to all four sides of the element.

Two-Value Padding

Using two values for the padding property will apply the first value to the top and bottom, and the second value to the left and right.

Three-Value Padding

With three values, the first value applies to the top, the second to the left and right, and the third to the bottom.

Four-Value Padding

Four values allow you to specify each side's padding: top, right, bottom, and left, in that order.

Using Percentage for Padding

Padding can also be defined using percentage values. The percentage is calculated based on the width of the containing block, which can be useful for responsive design.

Practical Example of CSS Padding

Below is an example that demonstrates how padding affects the layout of elements within a container. Notice how the padding changes the space between the content and the border.

Best Practices for Using Padding

Here are some tips for using padding effectively:

  • Use padding to improve the readability of text by spacing it from the borders.
  • Leverage the shorthand syntax for cleaner and more maintainable code.
  • Consider using relative units like percentages for responsive designs.
  • Test padding across different devices to ensure a consistent user experience.
Previous
Margin