Search code examples
htmlcssmargin

Why doesn't margin get filled with background color in CSS?


I have this simple piece of HTML.

Why doesn't the background color fill the entire #footer element's background - specifically, including the margin?

<!doctype html>
<html>

<head>
  <style>
    #footer {
      background: #263238;
      margin: 100px;
      padding: 0;
    }
    .footer-text {
      margin: 0;
      color: #fff;
    }
  </style>
</head>

<body>
  <div id="footer">
    <div class="footer-text">All Rights Reserved © 2016</div>
  </div>
</body>

</html>


Solution

  • You should use padding instead of margin as described by CSS's Box Model.

    • Margin is providing space beyond the element's box and therefore won't be colored - it's simply space.

    • Padding on the other hand provides space around the inside of the element's box and is colored and affected by other styles.

    <!doctype html>
    <html>      
      
      <head>
         <style>
            #footer {
               background: #263238;
               padding: 100px;
            }
            .footer-text {
               margin: 0;
               color: #fff;
            }
         </style>
      </head>
        
      <body>
         <div id="footer">
            <div class="footer-text">All Rights Reserved © 2016</div>
         </div>
      </body>   
     
    </html>