Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setting the margin on a div not affect the position of child content?

Tags:

html

css

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.

like image 220
devuxer Avatar asked Mar 07 '10 23:03

devuxer


1 Answers

This would be because the the div doesn't have an element to "push itself away from". It would seem that the select that comes before the div is floated. This causes it to be taken out of the normal page flow, and it doesn't act as reference for margin calculations anymore. The div is 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 submit on the other hand is very clear cut, since the frame of reference for it is the parent div.

like image 60
deceze Avatar answered Oct 03 '22 05:10

deceze