Why giving a margin-top to a div inside a div moves both divs downwards?

Im trying to center a small div inside a bigger one, both horizontal and vertical. When i give the small div a margin top it moves both divs downwards why is that? Is going with position relative and adjusting top and left the correct way or ill have other problems? The divs are both with % on the width

code:

<html>
<head>



<style>
#big_div{
  background-color:red;
  width:100%;
  height:200px;
}

#small_div{
  border:2px solid black;
  width:20%;
  height:80px;
}



                                

</style>
</head>
<body>

<div id="big_div">
  <div id="small_div">
  something
  </div>
</div>

</body>
</html>

Hi, @mouloudisg1

That’s called “collapsing margins”! :slight_smile:

Read more here: https://www.sitepoint.com/web-foundations/collapsing-margins/

Could be, but I suggest you try the table-cell display. Then you can align the small div as you please:

big_div{
    background-color:red;
    width:100%;
    height:200px;
    display:table-cell;
    vertically.align:middle;
    text-align:center;
}
small_div{
    border:2px solid black;
    width:20%;
    height:80px;
    display:inline-block;
}

The vertical-align affects the content whether block or inline.
The inline-block makes the small div center like a word would do.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.