Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child div margin in relation to parent div

Tags:

html

css

I have a simple child div nested inside a parent div, like so...

I am trying to understand why I cannot move the child div down (ex. 25px), in relation to the parent div, by using margin-top: 25px, unless I give the parent div a border. I am thinking that the child div is using the border as a reference point, which is why the margin-top actually works once the border is applied. That is all fine and dandy, but in the specific example I'm working on, the parent div has a background image, and I don't want to give it a border. But without a border, the child div won't move!

<body>

  <div id="main">

      <div id="child">
      </div>

 </div> 

</body

#main {width: 500px;
   border: 1px solid black;
   height: 500px;
   background-color: red;
   margin: auto;
   margin-top: 200px;
   }

#child {width: 100px;
    height: 100px;
    background: blue;
    position: relative;
    top: 5px;
   }
like image 458
JDH Avatar asked Dec 18 '25 17:12

JDH


2 Answers

I had this issue few days ago , I resolved it by adding a small padding (1px) to the parent div , and then use margin on the child div.

like image 77
RedhopIT Avatar answered Dec 21 '25 09:12

RedhopIT


You should rather give display:inline-block; property to child div.

like image 35
defau1t Avatar answered Dec 21 '25 08:12

defau1t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!