dotmartin
dotmartin

Reputation: 541

Surround a responsive image with divs

I have an image that I want to center in the middle of a div, the div can grow and shrink according to the size of the window, the image can also differ in size and should never be larger than the surrounding div.

I have managed to do this by using the following HTML:

<div class="imgspace">
  <img src="/variable.jpeg">
</div>

CSS:

.imgspace {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0; 
  right: 0;
}

.imgspace img {
  position: absolute;
  margin: auto;
  max-width: 100%;
  max-height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Now I want to implement a simple set of controls for the image. They should be layed out in three divs surrounding the image on the left, bottom and right side. The divs should grow and shrink with the image as it changes, both considering viewport size changes as well as actual image size.

Is this possible to achieve using only CSS or do I have to involve javascript?

Here's the starting point jsfiddle. I have intentionally left out the three surrounding divs since the placement in the DOM does not matter for me.

Upvotes: 1

Views: 158

Answers (1)

Jose Rui Santos
Jose Rui Santos

Reputation: 15319

I think you need to reserve some space for left, right and bottom elements.

In my example, I am reserving 10% for the #left and #right elements, leaving the img with a width 80%. Also, reserved 10% height for the #bottom element.

Hopefully this is what you are looking for: http://jsfiddle.net/6q4Ls/2/ Drag the separators to see how the elements react.


Another solution using elements outside your container, that seems simpler: http://jsfiddle.net/6q4Ls/5/


Edit Using fixed size http://jsfiddle.net/6q4Ls/9/

This might not work in all browsers, as I am using the calc() function.

div.imgspace img {
  position: absolute;
  margin: auto;
  max-width: calc(100% - 200px);
  max-height: calc(100% - 100px);
  top: 0; right: 100px; bottom: 100px; left: 100px;
}

Upvotes: 2

Related Questions