Css changing aspect ratio of fluid images

瘦欲@ 提交于 2019-11-30 07:41:23

问题


How can I crate a fluid image, but with an aspect ratio that I decide? (lets say 16:9)
I've already made it fluid with max-width: 100%; but I cant change the aspect ratio.

Note: the image has a different aspect ratio most of the times.


回答1:


You can wrapp your image in two containers. Give one container height:0 and a padding-top with the percentage you want for the height of your image in proportion to the width. So, for a height of 50% of the width use padding-top:50% and height:0, which - as explained here - will make the height proportional to the width by 50%.

.wrapper {padding-top:50%;height:0;position:relative;}

Inside of that container, you place another container with the following styling:

.inner{position:absolute;left:0;top:0;right:0;bottom:0;}

Now just place your image in the inner container and give it width:100% and height:100%

See fiddle: http://jsfiddle.net/henrikandersson/PREUD/1/ (updated the fiddle)




回答2:


I found this code on another post:

Example

CSS

.43 img { width: auto; }
.widescreen img { width: 100%; }
.portrait img { height: 100%; }

JavaScript

var getAspect = function(){
    var h = window.innerHeight;
    var w = window.innerWidth;
    var aspect = w / h;

    var 43 = 4 / 3;
    var cssClass = "";

    if (aspect > 43) {
        cssClass = "widescreen";
    }
    else if (aspect === 43) {
        cssClass = "43";
    }
    else {
        cssClass = "portrait";
    }

    $("body").addClass(cssClass); // Using jQuery here, but it can be done without it
};

var checkAspect = setInterval(getAspect, 2000);



回答3:


It would probably require extra markup in the HTML, but you could use the CSS Clip property to cut the visible portion of the image to what you would want to show. https://developer.mozilla.org/en/CSS/clip



来源:https://stackoverflow.com/questions/11399194/css-changing-aspect-ratio-of-fluid-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!