0

I have an overlay image that needs to be responsive vertically and horizontally to work on desktop and mobile.

Edit: By vertically responsive, I mean it needs to stay within the window and not overflow below the bottom of the screen.

There's a element on top of the image that needs to stay in the same place, and the image must retain its aspect ratio.

I'd rather do this with pure CSS, but could use JS for browser compatibility or a simpler solution.

http://codepen.io/brooksroche/pen/mEgJmd?editors=1100

<div class="container">
  <div class="img-container">
    <img src="http://placehold.it/300X200">
    <div class="example"></div>
  </div>
</div>

.container {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

.img-container {
  position: relative;
  margin: 0 auto;
  border: 1px solid red;
  width: 300px;
  max-width: 100%;
}

.img-container img {
  display: block;
  max-width: 100%;
  max-height: 100%;
}

.example {
  position: absolute;
  border: 1px solid blue;
  top: 40%;
  left: 30%;
  width: 38%;
  height: 20%;
}
Brooks Roche
  • 268
  • 4
  • 8
  • Have you looked for something like "Resize, but keep aspect ratio"? http://stackoverflow.com/questions/12991351/css-force-image-resize-and-keep-aspect-ratio Is this the problem, you got? – Tobias S Aug 18 '16 at 18:30

3 Answers3

0

Try setting the width and height to auto:

.img-container img {
display: block;
width: auto;
height: auto;
}

Or I have set the width or height, then auto the other which has worked.

Wayne
  • 146
  • 3
  • 13
  • That doesnt make it fit within the window vertically – Brooks Roche Aug 18 '16 at 19:06
  • I just had a play with @mehdi-dehghani 's codepen - It works if you remove 'display: flex;' from '.img-container' or add 'align-items: flex-start'. Don't know if this is an option. – Wayne Aug 18 '16 at 19:40
0

Check out CSS media queries.

The max-width and max-height CSS attributes should be able to solve your problem once you pick the appropriate breakpoints for the screen sizes you want to cover.

Check out this Stack Overflow post.

Community
  • 1
  • 1
0

Update

I just updated codepen & also putted the code here too.

<div class="container">
    <div class="img-container">
        <img src="http://placehold.it/500X300">
        <div class="example"></div>
    </div>
</div>

.container {
    border: 1px solid red;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: space-around;
    justify-content: space-around;
    -webkit-flex-wrap: wrap;
    flex-wrap: wrap;
}

.img-container {
    position: relative;
    overflow: hidden;      
    display: flex;      
}

.img-container img {
    display: block;
    max-width: 100%;
    margin: auto;
}

.example {
    border: 1px solid blue;
    height: 20%;
    position: absolute;      
    width: 100%;
    top: 50%;
    transform: translateY(-50%);      
}

Here is the working codepen

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64