centering an img within a div - both being resized

2019-09-03 19:52发布

问题:

I'm trying to center a resized image within its container (which should also be centered). I don't understand why this is so difficult, but I've been trying to get this working for 7 hours now. Please help :-)

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<link rel="stylesheet" href="styles.css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function imageresize() {
var conHeight = ($(window).height())* 0.56; 
    $(".resize").css({'height' : conHeight + 'px'}); // set large-image container to 56% of window height
}
$(document).ready(function() {
  imageresize();
});

$(window).resize(function() {
  imageresize();
});
</script>
</head>
<body>
<div id="navigation-area">
    <div id="navigation">
    </div>
</div>

<div id="set-overflow">
    <div class="resize" id="large-image">
        <img src="images/bg-home.jpg" class="resize">
    </div>
</div>
</body>
</html>

css:

/*------------------------------*/
* {
    margin: 0;
    padding: 0;
}
#navigation {
    width:990px;
    border:1px solid green;
    margin:23px auto;
    height:42px;
}
#navigation-area {
    width:100%;
    height:135px;
    background:url(images/bg-navigation.png) top center no-repeat;
    overflow:hidden;
    position:absolute;
    top:-3px;
    left:50%;
    margin-left:-50%;
    z-index:50;
}
#large-image {
    width:1970px;
    position:absolute;
    margin-left:-985px;
    left:50%;top:0;
    z-index:40;
    display:block;
}
#set-overflow {
    overflow:hidden;
    width:100%;
    height:100%;
    border:1px solid red;
    position:absolute;
    z-index:20;
}
.resize {
    margin-left:auto;
    margin-right:auto;
}

I need the overflow:hidden on the containing div as this will eventually be a single-page scrolling site and the large image is required only in the first div scrolled to. The image needs to be 56% of the viewport/window.

Please let me know whether I need to clarify anything.

MTIA

回答1:

Like this?

http://jsfiddle.net/9ZgWg/26/

Let me know if that's not what you're looking for and we can tweak it together.