I’m working on a graphics library that works a bit like the Android-type libraries and I ran into a question regarding the topic of margins and whose responsibility they should be.
It seems very common for graphics libraries to put the margin on the element itself; ie if you want to clear 10 pixels of space around an element in html/css, you do:
<div style="margin: 10px"></div>
Most of the libraries I see do the same thing, with the margin being set as a property of the child.
However, the point of margins seems to be to allow spacing out items inside a container, so that the different child elements don’t touch, or are easier to read. This means that in order to determine the margin, you must be aware where in the main page this element is going to be rendered, what will be shown around it, and how much room these other elements will have or need around them.
But the element itself should ideally not be aware where exactly it is being rendered on the page. This allows it to be reusable in different spots more easily.
For example, if you have a dialog with a set of buttons beneath it, and the buttons need to have 10 pixels of space between them, but the first and last one need to touch the edges of the dialog, then setting the margin on the children requires you to know exactly where in the list the child is.
For example, it could look like this:
<div class='dialog'>
<button style="margin-right: 10px">button 1</button>
<button style="margin-right: 10px">button 2</button>
<button>button 3</button>
</div>
Or it could look like this:
<div class='dialog'>
<button>button 1</button>
<button style="margin-right: 10px; margin-left: 10px;">button 2</button>
<button>button 3</button>
</div>
But in both cases, you can’t easily swap the buttons around because their order in the list matters, even though really it shouldn’t. Yet this seems to be how all the libraries do it. I implemented it the same way myself without thinking about it, but now I’m starting to wonder whether this is the right choice. Would it not be better to put the margin on the container instead?
<div class="dialog" style="space-out-children: 10px">
<button>button 1</button>
<button>button 2</button>
<button>button 3</button>
</div>
This makes the button completely uncaring about where it is being rendered and which elements may or may not be adjacent to it. I can easily use the same button in two locations, even if one requires a bit of space around it and the other should not.
So why is it that margin is made a property of the child instead of its container? Since everyone does it, I’m assuming there’s a good reason for it that I can’t figure out.
6