Web Elements Padding vs margin

Padding and Margin are sometimes confusing and you might use the wrong one for the wrong purpose. Both have a different impact according to how you use them. For me, I always have a secret on how to grasp this with a real-life scenario.

Let's say you're seated in a certain position in the house. The distance between you and the inner wall of the house is padding. This can be to the right, left, in front, or at the back of you. Let's say that the house sits on a rectangular fence plot. Margin is the distance between the outer wall of the house and the perimeter wall. The border is the wall

Definitions Margin is the outer space of an element while the padding is the inner space of an element

On opening the browser developer tools, under the element's styles, we can see how every element's dimension is measured. This image shows the element box model Screenshot 2022-06-28 at 05.46.02.png

Units of measurements

The small land size unit of measurement is always ft or meters. For web elements, you can use px, rem, em, pt, sm, in or dp to measure the margins and paddings. Check out more on css units

Element Positioning/Styling

Let's say you want to position your house in the center of the plot. All you've to do is get the exact measurements of the house length and width and the land size length and width. Subtract the land size width and length from the house width and length respectively. Divide two the result of each and you'll have the margin of your house. This concept applies to the padding and margins of the elements. You can position an element to the right/left/bottom/top or just center. Margin and padding inherit the position or take the default if none is provided. Let's say the parent element is position absolute, then the padding and margin will be measured as per the current position.

Note

  • Margins can be set to negative numbers while padding can't
  • Margins can be set to auto while padding can't
0
Subscribe to my newsletter

Read articles from Nicanor Talks Web directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nicanor Talks Web
Nicanor Talks Web

Hi there! I'm Nicanor, and I'm a Software Engineer. I'm passionate about solving humanitarian problems through tech, and I love sharing my knowledge and insights with others.