Search code examples
jqueryhtmlcssmargingsap

Margin Bottom 100% and Margin Top -100% not working


I'm having trouble understanding why my third div doesn't stack at -100% height when I use margin-top. I'm animating a movement of divs using Greensock and margin-left works perfectly for the first div. But when I try to move the upper div down, it is way higher. I know that height is based on width, but as far as I understand if I use 100% it shouldn't matter what the dimensions are. I tried using margin-bottom first but it didn't work. Any help would be greatly appreciated. Thank you. Here is the jsFiddle https://jsfiddle.net/kqyyq78q/

<body>
<a id="overlay"></a>
<div id="start">
<img src="http://imgh.us/roadtest1.svg" id="road" />
</div>
<div id="num1">
<img src="http://imgh.us/roadtest2.svg" id="road" />
</div>
<div id="num2">
<img src="http://imgh.us/roadtest3.svg" id="road" />
</div>
</body>

html,
body {
width: 100%;
height: 100%;
margin-top: 0;
margin-bottom: 0;
margin-right: 0;
margin-left: 0;
overflow: hidden;
font-size: 100%;
position: absolute;
}

#overlay {
z-index: 8;
position: fixed;
margin-left: 50%;
padding-top: 20%;
}

#road {
width: 100%;
height: auto;
}

#start {
width: 100%;
height: 100%;
position: fixed;
text-align: center;
}

#num1 {
width: 100%;
height: 100%;
position: fixed;
margin-left: 100%;
}

#num2 {
width: 100%;
height: 100%;
position: fixed;
margin-top: -100%;
}

Solution

  • What's happening is that you're using percentages on the margin as though they were relative to the image's height.

    Percentages for margin and padding are relative to the width. That means that your margin-top: -100%; rule will overshoot the mark whenever its width is not equal to its height. On the other hand, the css rule top: -100%; is based on the height, and will work.

    I've altered your code a bit to show a working example of this.

    #num2 {
      width: 100%;
      height: 100%;
      position: absolute;
      top: -100%;
    }