Css 如何在不拉伸或固定图像的情况下将图像保持在div内?

Css 如何在不拉伸或固定图像的情况下将图像保持在div内?,css,Css,我有这个html: <div class="postcard-container"> <div id="postcard-classic" class="postcard-classic"> <div class="postcard-classic-img"> <img ng-src="{{postcard.image.cropped}}" /> </div> &l

我有这个html:

<div class="postcard-container">
    <div id="postcard-classic" class="postcard-classic">
        <div class="postcard-classic-img">
            <img ng-src="{{postcard.image.cropped}}" />
        </div>
    </div>
</div>
我希望我的图像从左上角开始。如果它是一个非常小的图片,它应该被剪辑到左上角,如果它太大,我希望溢出不显示。让我们举一个例子,如果图像太大。我的目标是:

其中蓝色是图片,红色是div。如果图片太大,我从上面发布的代码中得到的信息如下:

我怎样才能解决这个问题

编辑


这就是我现在的处境。正如您所看到的,图像不是从左上角开始的,溢出也不是隐藏的。

您想要的行为应该是div中背景图像的默认行为。因此,您应该只需要backround image和background repeat属性

.postcard-classic {
  background-image: url("../img/frames/postcard_00.png");
  background-repeat: no-repeat;
}

您不应该为宽度指定任何值

 .postcard-classic-img {
    max-height: 100%;
    max-width: 100%;
 }

我想我可以接受这个解决方案:

使用flex解决方案

.postcard-classic-img{
    width:100%;
    height:250px;
    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden
}
.postcard-classic-img img{
     flex-shrink:0;
    -webkit-flex-shrink: 0;
    max-width:100%;
    max-height:100%;
}

你能提供一个提琴吗?这正是你想要做的:用一个提琴更新,忽略宽度会导致相同的结果。是的,我刚才说的是从中删除所有其他内容。不能这样做。它需要其他造型的东西。我发布了一个使用fiddle示例的工作解决方案。您的解决方案似乎可以缩小照片以适合盒子,您只需在图像本身上设置一个大小并添加一个黄色边框即可。您最初要求的是以父div的大小剪切图片,这与您的解决方案不同。此外,您最初在问题中使用了背景图像,但在您的解决方案中,您使用了嵌套在div中的图像标记,其行为也将有所不同。如果您对自己的解决方案感到满意,那就太好了。如果不是的话,你能澄清你的最终目标是什么吗。我使用的背景图像对我想要的没有影响。在这个例子中,我只是用背景色(黄色)替换了背景图像。重要的是图像的位置。照片缩小是一个意外,但对我来说似乎是一个更好的解决方案。
.postcard-container {
    width: 300px;
    height: 200px;
    position: absolute;
    display: table;
    padding: 20px;
}

.postcard-classic {
    display: table-cell;
    vertical-align: middle;
    background-color: yellow;
    overflow: hidden;
}

.postcard-classic-img {
    display: block;
    position: absolute;
    margin: auto;
    overflow: hidden;
    top: 10%;
    bottom: 10%;
    left: 8%;
    right: 8%;
}

.postcard-classic-img img {
    position: absolute;
    width: 100%;
    height: auto; 
}
.postcard-classic-img{
    width:100%;
    height:250px;
    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden
}
.postcard-classic-img img{
     flex-shrink:0;
    -webkit-flex-shrink: 0;
    max-width:100%;
    max-height:100%;
}