Image No Stretch or crop

喜欢而已 提交于 2019-12-02 03:06:48

问题


My question is simple. Let's say I have two rectangular images. The first is 200px wide and 100px tall, and the second is 100px wide and 200px tall.

I want to display the images with a constant width/height, e.g. 150px by 150px without stretching the images to fit:

I don't mind having whitespace/padding around the images. The problem is that the images could be of any width and height, and I want to limit them to a square box without stretching them.

The following CSS stretches the images to fit to 150px by 150px:

img {
    width: 150px;
    height: 150px;
}

The most preferable solution is CSS, even if I need a little more markup. JS/jQuery is okay as well though.


回答1:


What about:

img {
    max-height:150px;
    max-width:150px
}

To achieve your 2nd question on making smaller images bigger, you can do with jQuery. CSS could work if you knew the photo orientation before hand and applied a different css class to those images... But this will work and then you don't need the CSS max-width stuff any more.

<div class="container"><img src="images/DSC_0470.JPG" alt="Rad Image" /></div>

<script>
    $(document).ready(
        function () {
            $('.container img').each(
            function () {
                var theWidth = $(this).width();
                var theHeight = $(this).height();
                if (theWidth < theHeight) {
                    $(this).height(150);
                }
                else {
                    $(this).width(150);
                }

            });
        });</script>



回答2:


You should be able to use the max-width and max-height properties, like so:

img {
    max-width: 150px;
    max-height: 150px;
}

This should constrain it to that box without stretching it.

If you want to make sure that each appears in a square box of size 150px by 150px, you could contain each image in a container div, and force them to be exactly that size:

<div class="container">
  <img>
</div>

with the following CSS:

img {
    max-width: 150px;
    max-height: 150px;
}
.container {
    width: 150px;
    height: 150px;
}



回答3:


Try this format...

<img src="image.jpg" style="border:none;position:absolute; top:20px; left:50px; width:100px; height:200px;">


来源:https://stackoverflow.com/questions/13333699/image-no-stretch-or-crop

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