简体   繁体   中英

CSS: How to make a div the same size as a height-constrained image

I have been trying to make div the exact same size as an image, but I don't know the aspect ratio of the image and I wish the image to fit the entire height of the webpage.

I have some experimentation at jsfiddle using display:inline-block

http://jsfiddle.net/jxKqp/4/

and while it seems to look ok when the webpage is loaded in chrome, if the webpage is resized, it fails to conform properly. In firefox it doesn't work at all. Perhaps there's a better way to go about constraining a div to an image?

Here's similar code inline

<!HTML>
<html>
 <head>
 <style type="text/css">
 .background_image {
   height:100%;
   width:auto;
   border: 5px solid #ff0000;
 }
 body {
  overflow:hidden;
 }
 div.container {
   position:relative;
   display:inline-block;
      border: 5px solid #00ff00;
  }
  div.inner {
     position:absolute;
     top:0;bottom:0;left:0;right:0;
     border: 5px solid #0000ff;
     border-style:groove;
     z-index:2;
     background:black;
     color:white;
     opacity:.5
}
</style>
</head>
<body>
<div class="container"> 
  <img    src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Henry_ford_1919.jpg/470px-Henry_ford_1919.jpg" class="background_image"/>
  <div class="inner">
    I want to be same size as the image
  </div>
</div>

​ `

Take out all this stuff:

 .background_image {
   height:100%;
   width:auto;
   border: 5px solid #ff0000;
 }
 body {
  overflow:hidden;
 }

DEMO

If you want the div to adjust as you resize, I believe you will need JavaScript. You could easily use jQuery's resize() function to do what you're talking about.

I added the following code to your fiddle:

$(document).ready(function(){
    $(window).resize(function(){
        $('.inner').height($(window).height());
    });        
});​

And that will resize the div to be the height of the window (which will also be the height of the image as you're defining it).

See new fiddle here: http://jsfiddle.net/jxKqp/7/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM