Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - Vertical centering variable height image while maintaining max-width/height

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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%).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...