Jimmy
Jimmy

Reputation: 3850

Auto-sizing a parent div

I am wanting to put a child image, with its size adjusted, inside a parent div. How do I get this parent div's with to be the same, and not bigger, than the child image? See the below snipppet for an example. Thanks.

div {
  border: 1px solid blue;
  width: auto;
  height: auto;
  display: inline-block;
  overflow: auto;
}

img {
  background-color: orange;
  width: 80%;
  height: 80%;
  overflow: auto;
}
<div>
  <img src="https://www.python.org/static/opengraph-icon-200x200.png" />
</div>

Upvotes: 0

Views: 49

Answers (2)

Fabio Vella
Fabio Vella

Reputation: 434

The fact that you are using a percentage for the img size is the problem. You are saying that your image has to be 80% of the parent div therefore you are explicitly telling the img not to fill the whole div. The other problem you have is that an image is an inline element, if you change that to block it will remove the extra space at the bottom of the image.

See the CSS

div {
  border: 1px solid blue;
  display: inline-block;
}

img {
  background-color: orange;
  display: block;
  width: 90px;
  height: 90px;
}

Also a Pen

I hope it helps!

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

In that case, you need to have the width of the img to be 100% and have the width or something of 80%:

div {
  border: 1px solid blue;
  width: auto;
  height: auto;
  display: inline-block;
  overflow: auto;
}

img {
  background-color: orange;
  display: block;
}
<div>
  <img src="https://www.python.org/static/opengraph-icon-200x200.png" />
</div>

Preview

preview

Upvotes: 3

Related Questions