giving child div a margin relative to the parent div
Solution 1
Maybe this could help: CSS Margins Overlap Problem
Add position property to both elements. Parent is relative
and child is absolute
...
.parentDiv {
position: relative;
margin-top: 200px;
width: 700px;
height: 800px;
background-color: red;
}
.childDiv {
position: absolute;
background-color: green;
width: 50px;
height: 50px;
margin-top: 22px;
}
Here's your fiddle: http://jsfiddle.net/algorhythm/1whywvpa/5/
Solution 2
It looks like the .childDiv
isn't floated left.
If you float: left;
the .childDiv
, as I have in JS Fiddle, it will apply the margin as required.
Solution 3
You don't want to use margin in this case. You should add padding to the parent div. You also need to close your parent div. So remove the margin-top:22px
on the child div. Add padding-top:22px;
on the parent div.
SilentDev
Updated on June 11, 2022Comments
-
SilentDev almost 2 years
This is my html:
<div class='parentDiv'> <div class='childDiv'></div> </div>
and this is my CSS:
.parentDiv { margin-top: 200px; width: 700px; height: 800px; background-color: red; } .childDiv { background-color: green; width: 50px; height: 50px; margin-top: 22px; }
the fiddle: http://jsfiddle.net/1whywvpa/
How come childDiv does not get the margin-top of 22px? It only gets a margin top if the pixels is greater then the 200px which is already given to the parentDiv. Any way to make the childDiv get a parent div of 22px relative to the parentDiv without doing some type of 'give the parent div a 1px padding' hack?