1

I have a div with a height that is set to window height by using some JS, and an image that is vertically and horizontally centered. While using max-width: 100% on the image, I can get it to scale when the width is resized, but I want to know how to scale the image when the window is resized vertically. Any help or suggestions on how to solve this would be appreciated.

EDIT:

I'm stupid. I forgot to mention that I have texted on the bottom of the image, and when you scale vertically, the text overlaps the image. I'm trying to solve this by scaling the image vertically.

HTML:

<div class="main">
    <img class="img-resp img" src="path/to/img.jpg">

    <h1>Big Bold Headline</h1>
</div>

CSS

html,body { height: 100%; }
.main { background: black; position: relative; }
.img-resp { display: block; max-width: 100%; }
.img { position: absolute; top: 50%; left: 50; margin: 0 -100px 0 -100px; }

JS

var windowHeight = $(window).width();

$('.main').height(windowHeight);
alyus
  • 987
  • 4
  • 20
  • 39
  • 1
    Check the [link](http://stackoverflow.com/questions/18516317/vertically-align-an-image-inside-a-div-with-responsive-height). It may help. Good Luck! – S M Jan 14 '16 at 05:53

3 Answers3

1

Try Like this-

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

It will make responsive vertical/horizontal image centering with CSS only

also check this link- Vertically align an image inside a div with responsive height

Community
  • 1
  • 1
Satish Shinde
  • 2,878
  • 1
  • 24
  • 41
  • I have text below the image, and when scaled the text overlaps. Is there anyway to fix this? – alyus Jan 14 '16 at 19:19
0

You can try this

HTML

<div class="main">
    <div class="dummy"></div>
    <div class="img-container">
        <img src="path/to/img.jpg" alt="" />
    </div>
</div>

CSS

.main {
    position: relative;
    width: 100%;
    border: 1px solid black;
}

.dummy {
    padding-top: 100%; /* forces 1:1 aspect ratio */
}

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
Lakshya
  • 506
  • 1
  • 4
  • 20
0

That is because you haven't given width or height to your image, so try this code.

<!DOCTYPE> 
<html>
<head>
    <title></title>
    <link rel="stylesheet" src="path"/> <!-- this if your use external sheet-->

<style>
  body{
    background-color:pink;
  }
</style>

</head>
<body>

<div style="width:100%;height:auto;">
  <img style="width:100%;height:100%" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSO8LcKZte0hFbIRmnOtoX8FF4L_Ln1oOwMYb_oWQRs2qO8i3W6">
</div>


</body>
</html>
caldera.sac
  • 4,918
  • 7
  • 37
  • 69