2

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;
   }
JDH
  • 35
  • 1
  • 7
  • does the parent div have its position defined?? – nandu Aug 25 '12 at 19:45
  • possible duplicate of [Why does this CSS margin-top style not work?](http://stackoverflow.com/questions/9519841/why-does-this-css-margin-top-style-not-work) – BoltClock Aug 25 '12 at 19:47
  • You're right, it's a similar question, but I think the accepted answer is much more clear and concise on this question, and would recommend not closing the quesiton. – JDH Aug 25 '12 at 19:54
  • Can replicate the problem. Tried it out here.http://jsfiddle.net/sshekhar_1987/n4NV7/ if there is something else could you please elaborate. – heretolearn Aug 25 '12 at 19:54
  • Thank you for that sshekhar, that's actually the best solution. Not sure how I overlooked that – JDH Aug 25 '12 at 20:00

2 Answers2

7

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.

RedhopIT
  • 609
  • 2
  • 7
  • 20
  • Thanks! That worked perfectly. Although I added the margin-top needed for the child div, to the padding top of the parent div and it put my child div right where it needs to be. Not sure if this is the best solution, but it works – JDH Aug 25 '12 at 19:50
  • Genius - this works. I had to add width:102% to the child and then overflow:hidden to the parent to get all the alignments squeaky clean. – Eeeeed Jul 01 '17 at 12:59
5

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

defau1t
  • 10,593
  • 2
  • 35
  • 47
  • That didn't work for me. As soon as I did that, it removed the margin: 0 auto that I had applied to the child div – JDH Aug 25 '12 at 19:56