Today, while working on a tiny project, I suddenly wondered why I usually favor margins instead of paddings to create space around elements in CSS. At the moment, given that there are deadlines, I decided to push aside the question, but before that I did a quick search, and opened a Stack Overflow question about the matter so I would not forget about this existential question of mine.
At some point during that tiny project, I came up with a situation that definitely required paddings, and not margins to solve. The situation was this: I had two elements in a sort of lightbox effect. I wanted the “lightbox” to close whenever the user clicked on the element that was sitting behind covering the full window, but not when the user interacted with the element sitting in front, ie the content of the lightbox. The solution was simple, add a click event handler on the back element that closed the lightbox, and a click event handler in the content element that only stopped the propagation of the event. That way whenever the user interacted with the content element the click event would never reach the back element, thus not closing the lightbox.
This method worked well, but I wanted users to have a little room around the content where they could safely click without closing the lightbox. For this, using a padding on the content element was the way to go. In this situation a margin would not have worked because you can ‘t click the margin of an element. Clicking the element was required because only that way could we prevent the click event from bubbling up to the back element.
In the stack overflow question, someone mentions that they usually use padding only when they want to increment the space inside a visible box. I’ve now presented you with another case, although this ones is more of an edge case.
I think most of us prefer margins, but there are cases where padding is the right and maybe only way to go.