Skip to main content
Practice

Padding

In CSS, padding refers to the inner spacing of an element.

Padding creates space between the content of an element (text, images, etc.) and its border.

Unlike margin, padding affects the actual size of the HTML element. In other words, adding padding can increase the overall size of an HTML element.


Usage

  1. Setting padding for all sides: You can set padding for all sides at once.

    CSS
    .box {
    padding: 20px; /* Set 20px padding on all sides */
    }

  1. Setting padding individually: You can set padding for each side in the order of top, right, bottom, left.

    CSS
    .box {
    padding: 10px 15px 20px 25px; /* Set padding for top, right, bottom, left */
    }

    The above code is equivalent to setting the padding for each direction as follows:

    • 10px : Top padding
    • 15px : Right padding
    • 20px : Bottom padding
    • 25px : Left padding

  1. Using shorthand properties:

    CSS
    .box {
    padding-top: 10px; /* Top padding */
    padding-right: 15px; /* Right padding */
    padding-bottom: 20px; /* Bottom padding */
    padding-left: 25px; /* Left padding */
    }

    You can also set the padding for each direction separately in this way.


Caution

  • padding affects the overall size of the element. For example, adding padding: 10px to a box of size 100px by 100px will increase the overall size of the box to 120px by 120px because it adds 10px of inner spacing on all sides.

  • To prevent this, you can use box-sizing: border-box; to ensure that padding does not affect the overall size of the element. In the earlier example, adding box-sizing: border-box; to the CSS of a 100px box will ensure that the overall size of the box remains 100px by 100px even if 10px of padding is added.

    CSS
    .box {
    box-sizing: border-box;
    }

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.