问题
I have a project, where I have 4 images together in the middle of the window, laid out like this:
12
34
I want the images to all scale up and down with the window, but maintain their position.
Right now, I have them all in a div called Center:
<div style="max-width:1200px;" id="centerArrows">
<img src="images/homePage/arrowUL.png" style="position: relative; top: -100px; float:left;" />
<img src="images/homePage/arrowUR.png" style="position: relative; left: 40px; top: -95px;" />
<img src="images/homePage/arrowDL.png" style="position: relative; left: -35px; top: -80px;" />
<img src="images/homePage/arrowDR.png" style="position: relative; left: 670px; top: -510px;" />
</div>
with this CSS:
#centerArrows {
margin-top: auto;
margin-left: auto;
margin-right: auto;
margin-bottom: auto;
position: relative;
z-index: 0;
width: auto;
}
img {
width: auto;
max-width: 100%;
max-height: 100%;
}
Any idea what I'm doing wrong?
回答1:
See this fiddle:
http://jsfiddle.net/LDt8P/
html , body , #centerArrows{
display:table;
width:100%;
height:100%;
}
#centerArrows{
display:table-cell;
text-align:center;
vertical-align:middle;
}
Fiddle in response to the comment to restrict the image from spreading out to 4 lines:
http://jsfiddle.net/LDt8P/1/
Solution with JQuery to make the image smaller to fit the width of the window when the window width is smaller that a specific width:
http://jsfiddle.net/LDt8P/3/
回答2:
var initialWidth = $(window).width();
$(window).resize(function(){
$('img').each(function(){
var img = $(this),
pos = img.data('pos') || $(this).offset(),
imgWidth = img.data('width') || img.width(),
ratio = $(window).width() / initialWidth,
newImgWidth = imgWidth * ratio,
newImgLeft = pos * ratio;
img.css({
width: newImgWidth + 'px',
left: newImgLeft + 'px'
});
});
}).resize();
Here is a simple jQuery implementation. In this case you have to use position: fixed or position: absolute (in this case the elements relative parent should be the body.
The code is untested... (sorry, i don't really have time now)
来源:https://stackoverflow.com/questions/20966794/how-to-make-image-elements-scale-with-window-instead-of-repositioning