CSS Negative Margins Example
Out of all pieces in the floating CSS design model, margins are probably the easiest to understand for a newcomer. A margin property in CSS is, technically, the space between that element and another one next to it. Things get, however, a bid mind-boggling when margins have negative values. Here's a quick example, followed by some explanations.
HTML Example:
CSS Example:
#div1, #div2 {
width: 100px;
height: 100px;
}
#div1 {
background:red;
margin-bottom: 10px;
}
#div2 {
background: blue;
margin-left: 50px;
margin-top: -60px;
}
Result:
The second div box has a top margin of -60 pixels which made the two rectanges overlap. The margin-bottom property of the first div pushed the second one 10 pixels below, while the second one's negative margin-top pushed it 60 pixels above. As a result, the two overlapped halfway through (at exactly 50 pixels, grab a ruler and measure the distances if you don't want to take my word for it).
As a homework, experiment with various top and bottom margins in the two div boxes and explain what happened.
Share Tweet