垂直中心变量高度图像,同时保持最大宽度/高度 [英] Vertical centering variable height image while maintaining max-width/height
问题描述
我想将一个未知宽度/高度的图片放在页面上,如果它大于页面,请确保它缩小(例如使用 max-width
/ max-height
)。
我尝试使用
display:table-cell
方法,但是在 display:table-cell $>声明的元素内的所有元素在Firefox中忽略 max-width
c $ c>。有没有办法垂直居中一个可变高度的元素,而不使用 display:table-cell
?
改变标记。 JavaScript是可以接受的,但我不能使用JQuery(或任何其他JS库)。
解决方案 ..不需要JavaScript:)
请参阅 jsFiddle的工作演示。
CSS
*不要更改 - 定位* /
.absoluteCenter {
margin:auto;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}
/ *调整大小* /
img.absoluteCenter {
max-height:100%;
max-width:100%;
}
HTML
< img class =absoluteCentersrc =PATHTOIMAGE>
注意:此类别可以轻松使用。如果您将此图片用于图片之外的其他图片,请务必添加 TAG.absoluteCenter
CSS规则,其中包含 max-height
和 max-width
(其中 TAG
是您使用的HTML标记[例如 div.absoluteCenter
]和 max-width
/ max-height
100%
)。
I want to center an image of unknown width/height on a page, while making sure that it shrinks if it is bigger than the page (i.e. use max-width
/max-height
).
I tried using the display:table-cell
method, but max-width
is ignored in Firefox for all elements within elements declared with display:table-cell
. Is there a way to vertically center a variable-height element without using display:table-cell
?
I can change the mark up. JavaScript is acceptable, but I cannot use JQuery (or any other JS library).
解决方案 This should prove to work quite well... no JavaScript necessary :)
See the working demo on 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">
Note: This class can be used for anything quite easily. If you use this for something other than an image, make sure to add a TAG.absoluteCenter
CSS rule with a max-height
and max-width
of your choosing (where TAG
is the HTML tag you're using [e.g. div.absoluteCenter
] and max-width
/max-height
is less than 100%
).
这篇关于垂直中心变量高度图像,同时保持最大宽度/高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!