0
votes

I was trying to get my header background image to reach the top of the viewport. There was a gap between the top of my image and the top of the viewport, and I wanted to fix it. I tried applying a margin to my <header> css, but this did nothing. What DID end up working was applying padding.

 header {
      text-align: center;
      background: url("https://i.imgur.com/E4yIQba.jpg");
      background-size: cover;
      color: white;
      padding: 1px 0px 0px 0px;

    }

Everything looks good now, but does anyone know why adding 1px of PADDING to the top of the image resolved the issue, while attempting to add a MARGIN of 0px(margin: 0px 0px 0px 0px) did nothing? I thought margins were supposed to move elements closer and farther away from the edges of viewports. I am surprised that padding resolved my issue instead of margin. Thanks!

https://dash.generalassemb.ly/docmp0/build-your-own-blog-theme

1

1 Answers

1
votes

Actually, margins are considered to be outside of the element, and margins of adjacent items will overlap, but on the other hand, paddings are considered to be inside of the element. So indeed an element's padding area is the space between its content and its border when an element margin area is a space between that element and elements around it.

So let's see this in an example.

div.container {
  display: flex;
  justify-content: space-between;
}

div.box>div {
  height: 50px;
  width: 50px;
  border: 1px solid black;
  text-align: center;
}

div.padding>div {
  padding-top: 1rem;
}

div.margin>div {
  margin-top: 1rem;
}
<div class="container">

  <div>
    <h3>Default</h3>
    <div class="box">
      <div>box A</div>
      <div>box B</div>
      <div>box C</div>
    </div>
  </div>

  <div>
    <h3>padding-top: 1rem;</h3>
    <div class="box padding">
      <div>box A</div>
      <div>box B</div>
      <div>box C</div>
    </div>
  </div>

  <div>
    <h3>margin-top: 1rem;</h3>
    <div class="box margin">
      <div>box A</div>
      <div>box B</div>
      <div>box C</div>
    </div>
  </div>
</div>

So as you can see in the example adding padding to each box will result in growing them in padding area, this will work the same for images.

Consider the following image as a content box, whenever you add padding it will apply to the innermost part of a box, and whenever you add margin it will apply to the outermost part of a box.

enter image description here

NOTE: Read more information about padding and margin.