How Is CSS Percentage Padding Calculated?

CSS padding can be defined using percentage values, in which case, it's calculated relative to the width of the containing element. This holds true for all sides, be it padding-top, padding-right, padding-bottom or padding-left.

For example:

#parent { width: 300px; }
#child {
  padding: 10% 5%; /* padding-top / bottom = 30px, padding-right / left = 15px */
}

Based on this example, the #child element's padding is computed as follows:

  1. padding-top and padding-bottom: 10% of the width of #parent (30px each);
  2. padding-right and padding-left: 5% of the width of #parent (15px each).

If the containing block's width changes, the percentage-based padding adjusts accordingly. This behavior is particularly useful for creating responsive layouts, as it allows you to maintain consistent spacing and proportions relative to the parent element's width across various screen sizes or content changes.

To see this in action, try changing the width in the example below:

padding: 10% 5%
#parent
  width: 100%
  height: auto
#child
  padding-top: 54px
  padding-right: 27px
  padding-bottom: 54px
  padding-left: 27px

This example illustrates that only toggling the parent's width impacts the calculation of the padding percentages, and not the height. For padding-top and padding-bottom this might seem counterintuitive, but it's a consistent aspect of how CSS interprets percentage-based padding.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.