CSS: margin of an img inside of div

Viewed 35

I have this CSS rule for the image:

.post-img {
  width: 100%;
  height: auto;
  margin: 100px; 


}

I set margin:100px for the .post-img, we know that this image takes the width of his parent, but why when we set this margin it goes outside of the header (parent element), it not supposed to fit inside his parent?

https://i.stack.imgur.com/bncP8.jpg

https://i.stack.imgur.com/gkbJJ.jpg

2 Answers

is everything ok? first you set the width to 100%, so the img has the same width as the parent. You can use calc() to reduce the width of the img on both sides, see:

.post-img {
            width: calc(100% - 200px);
            margin: 100px;
        }

You could get the effect by using padding instead of margin and setting box-sizing to border-box (which will include the padding as part of the element's overall dimensions).

Here's a simple example:

* {
  margin: 0;
}

.parent {
  width: 500px;
  background: #eeeeee;
}

.post-img {
  width: 100%;
  height: auto;
  padding: 100px;
  box-sizing: border-box;
}
<div class="parent">
  <img class="post-img" src="https://picsum.photos/id/1016/200/100">
</div>

Related