Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

giving child div a margin relative to the parent div [duplicate]

Tags:

html

css

margin

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?

like image 844
SilentDev Avatar asked Sep 21 '14 21:09

SilentDev


1 Answers

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/

like image 101
algorhythm Avatar answered Oct 20 '22 05:10

algorhythm