Erran
Erran

Reputation: 171

How to size div relative to image size

What I want:

I have a PNG image of a shirt which has an clear background, and I want to place it on top of a colored square, such that the shirt in the image will "pop" over the edges of the square, for decorative purposes. The width of the image is set to 100%, and the height is set automaticaly to keep the original ratio. If the window is resized, the squares height and width should be relative to the images height and width, and should resize responsively alongside the image.

What I've tried:

What is using a div for the decorative square, and a img html element for the image, and placing them both in a container:

This is the CSS for the square:

.square {
    width: 80%;
    height: 80%;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10%;
    background-color: red;
    z-index: -1;
}

CSS for the image:

.shirtImage {
    width: 100%;
    margin-left: auto;
    margin-right: auto;
}

And the container is simply a div.

The Problem:

The height of 80% set for the square is relative to the the whole page, all the way to the bottom, instead of just the div wrapping the image and the square.
I realize that this method is bound not to work since i'm expecting the square to infer its height from the parent (the wrapping div) which infers its height from another child (the image), but can't quite understand entirely why it isn't working, and can't figure out how to do it.

Upvotes: 0

Views: 533

Answers (1)

G-Cyrillus
G-Cyrillus

Reputation: 105853

you need to use a pseudo, so the div becomes the parent , and from there use vertical padding or margin to sretch the div into a square. Image can be layed in absolute to avoid modifying height of the div.

https://developer.mozilla.org/en-US/docs/Web/CSS/padding

<percentage>

The size of the padding as a percentage, relative to the width of the containing block.

possible example

.square {
  width: 80%;
  height: 80%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 10%;
  background-color: red;
  z-index: -1;
  position: relative;
  overflow: hidden;
}

.square:before {
  content: '';
  display: block;
  padding-top: 100%;/* equals width of parent */
}

.shirtImage {
  width: 95%;/* 95 instead 100 for the demo*/
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom:0;
  right:0;
}
<div class="square">
    <img class="shirtImage" src="http://dummyimage.com/100/fe0">
</div>

Upvotes: 1

Related Questions