垂直居中可变高度图像,同时保持最大宽度/高度
Vertical centering variable height image while maintaining max-width/height
我想将宽度/高度未知的图像居中放置在页面上,同时确保它在大于页面时收缩(即使用max-width
/max-height
)。
我尝试使用display:table-cell
方法,但对于用display:table-cell
声明的元素中的所有元素,在Firefox中都会忽略max-width
。有没有一种方法可以在不使用display:table-cell
的情况下垂直居中可变高度元素?
我可以更改标记。JavaScript是可以接受的,但我不能使用JQuery(或任何其他JS库)。
这应该能很好地工作。。。无需JavaScript:)
请参阅jsFiddle上的工作演示。
CSS
/* Don't Change - Positioning */
.absoluteCenter {
margin:auto;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}
/* Sizing */
img.absoluteCenter {
max-height:100%;
max-width:100%;
}
HTML
<img class="absoluteCenter" src="PATHTOIMAGE">
注意:这个类可以很容易地用于任何事情。如果您将其用于图像以外的其他内容,请确保添加一个TAG.absoluteCenter
CSS规则,其中包含您选择的max-height
和max-width
(其中TAG
是您正在使用的HTML标记[例如div.absoluteCenter
],max-width
/max-height
小于100%
)
试试这样的。。。
演示:http://jsfiddle.net/wdm954/jYnk8/1/
$(function() {
h = $('.img').height();
w = $(window).height();
if (h < w) {
$('.img').css('margin-top', (w - h) /2 + "px");
}
else {
$('.img').height(w);
}
});
(您可以通过更改我注释掉的一些CSS来测试不同的大小。)
以下是javascript的一种方法:
<html>
<head>
<style>
html, body{
height:100%;
margin:0;
border:0;
padding:0;
background:#000;
}
body{
position:relative;
}
img{
border:0;
padding:0;
margin:0 auto;
max-width:100%;
max-height:100%;
display:block;
position:absolute;
}
</style>
</head>
<body>
<img />
<script>
(function(){
var imgs = [
'http://farm3.static.flickr.com/2396/2078094921_ee60c42d0f.jpg',
'http://farm6.static.flickr.com/5242/5353846171_9169f810dc_b.jpg',
'http://farm6.static.flickr.com/5284/5336493514_8e41696b66_b.jpg'
],
img = document.getElementsByTagName('IMG')[0],
getStyle = function(elm){
return window.getComputedStyle ? window.getComputedStyle(elm) : elm.currentStyle;
},
bodyStyle = getStyle(document.body),
toInt = function(pxSize){
return +pxSize.replace(/px/,'');
},
chgImg = function(){
img.src = imgs[i++ % imgs.length];
img.onload = function(){
var imgStyle = getStyle(img);
img.style.left = ( toInt(bodyStyle.width) - toInt(imgStyle.width) ) / 2 + 'px';
img.style.top = ( toInt(bodyStyle.height) - toInt(imgStyle.height) ) / 2 + 'px';
img.onload = null;
};
},
i = 0;
chgImg();
setInterval(chgImg, 3000);
})();
</script>
</body>
</html>
相关文章:
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- 如果宽度是百分比,如何设置以px为单位的图像高度
- 根据图像高度添加类
- 图像宽度和高度,无拉伸或溢出
- 自动缩放图像以匹配文本高度
- 使用asp.net FileUpload时从javascript获取图像宽度和高度
- whay可以't我使用javascript同时更改图像的高度和宽度
- Cloudinary上传小部件-样式上传预览图像(宽度和高度)
- 尝试使用window.innerHeight和Javascript设置图像高度
- 如果我将宽度调整为另一个值,找出我的图像的高度
- Javascript图像宽度和高度未定义值
- 我想根据容器中包含的图像设置容器的高度
- 高图表图像渲染器自动高度
- 灯箱类型的东西,使图像成为浏览器高度的百分比
- 如何在浏览器宽度/高度变化时动态调整图像网格的大小
- 当溢出-x 设置为隐藏时处理可变高度图像的最佳方法是什么?
- 在画布HTML5中查找上传的宽度和高度图像.(带文件读取器)
- 使用JavaScript查找图像的高度-图像加载错误
- 将悬停效果应用于响应高度图像
- 垂直居中可变高度图像,同时保持最大宽度/高度