问题
I've always thought I understood margins and negative margins but apparently I don't! I've just started a new design and running into problems already.
I have a div (hill3Cont) and another div (hill3Hill) nested inside, and this is the CSS for them.
#hill3Cont
{
width: 100%;
background-image: url("images/grass.jpg");
}
#hill3Hill
{
margin: -100px 0 0 0;
height: 600px;
width: 100%;
background: url("images/hill3.png") no-repeat center top;
}
I have applied a negative margin to the top of the child div in the hope it will push this content up outside the boundaries of the parent div. But it doesn't, it doesn't move. If I apply a positive margin it pushes the parent div down along with the child inside it.
The only way I can make it behave properly is use a border or overflow hidden on the parent div, but the design won't allow for either of these (I don't want a border and overflow hidden hides the child).
Maybe it's just been a long day and I'm missing something common! Many thanks in advance.
Edit: I have got a solution, I've put a single padding top on the parent div, padding: 1px 0 0 0. It works for my design so I'm happy but still keen to find out what's happening.
回答1:
Sounds like a problem with collapsing margins:
http://www.seifi.org/css/understanding-taming-collapsing-margins-in-css.html
回答2:
For child inside parent element use position relative and negative top instead.
http://jsfiddle.net/GEwj3/3/
#hill3Cont
{
margin-top: 50px;
width: 200px;
height: 200px;
background-color: red;
}
#hill3Hill
{
height: 50px;
width: 100px;
background: blue;
position: relative;
top: -20px;
}
回答3:
It's not clear to me that negative values for margin are supposed to give the behaviour you want, rather than being treated as zero. I would just avoid them as potentially undefined behaviour.
回答4:
http://jsfiddle.net/XVanj/2/ check this one out as well
来源:https://stackoverflow.com/questions/5750088/margins-and-negative-margins