I’d like to understand a little more clearly how css margins work with divs and child content.
If I try this…
<div style="clear: both; margin-top: 2em;">
<input type="submit" value="Save" />
</div>
…the Save button is right up against the User Role (margin fail):
Margin Fail 🙁 http://img697.imageshack.us/img697/8459/nomargin.jpg
If I change it to this…
<div style="clear: both;">
<input style="margin-top: 2em;" type="submit" value="Save" />
</div>
…there is a gap between the Save button and the User Role (margin win):
Margin Win 🙂 http://img20.imageshack.us/img20/1973/yesmargin.jpg
Questions:
Can someone explain what I’m observing? Why doesn’t putting a margin on the div cause the input to move down? Why must I put the margin on the input itself? There must be some fundamental law of css I am not grasping.
This would be because the the
divdoesn’t have an element to “push itself away from”. It would seem that theselectthat comes before thedivis floated. This causes it to be taken out of the normal page flow, and it doesn’t act as reference for margin calculations anymore. Thedivis clearing the float, i.e. it drops below it, then tests if there’s a 2em margin to the next element above it that is within the same “flow”. Apparently there is, so it doesn’t move down any further.Setting the margin on the
submiton the other hand is very clear cut, since the frame of reference for it is the parentdiv.