问题
I'm designing the mobile phone portion of my website. I have a, top:0%, position:fixed, banner image with, width:100%, and height:auto. As the phone is turned horizontally the banner image scales nicely covering the screen width.
However my issue is in positioning content below this image. For example a div with position:absolute, and top:20%, displays a div below the banner for a vertical screen. Unfortunately when turning the screen horizontally, the image enlarges, and covers the div. Is there a CSS solution that can grab the height of the image at any point and adjust its top percentage accordingly?
Edit: I'm also open to a javascript solution :) Thanks.
回答1:
Here is one way of doing it.
For example, if this is the HTML:
<div class="header">
<img src="http://www.placekitten.com/400/100">
</div>
<div class="main">Some content...</div>
You can use the following CSS to fix-position your header and absolute-position your main block:
.header {
position: fixed;
top: 0px;
left: 10px;
right: 10px;
border: 1px dotted blue;
}
.header img {
width: 100%;
vertical-align: top;
}
.main {
border: 1px solid blue;
position: absolute;
top: 147px;
left: 10px;
}
To automatically reposition your .main
block when the window re-sizes, you can use
the following jQuery:
function fixMainTop() {
$(".main").css({
"top": $(".header").outerHeight()
});
}
fixMainTop();
$(window).resize(function () {fixMainTop();});
You call the fixMainTop()
when the page load, and then whenever the window size changes.
However, the $resize
function can lead to slightly jumpy looking screen, but I think that you can accept that since many websites using jQuery exhibit the same behavior.
Demo fiddle: http://jsfiddle.net/audetwebdesign/spxCj/
PS
You may not need the .resize
action if the website has a fixed width... but it is good to see how it can be done.
来源:https://stackoverflow.com/questions/17132850/css-image-with-heightauto-covers-div-beneath-it-upon-screen-resize-phone-hel