css - 如何在不拉伸(stretch)或固定图像的情况下将图像保留在 div 中?

标签 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>
    </div>
</div>

还有这个 CSS:

.postcard-container {
    position: absolute;
    display: table;
    width: 100%;
    height: 100%;
    padding: 20px;
}

.postcard-classic {
    display: table-cell;
    vertical-align: middle;
    background-position: center center;
    background-image: url("../img/frames/postcard_00.png");
    background-size: contain;
    background-repeat: no-repeat;
    padding: 10px;  
}

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

我希望我的图像从左上角开始。如果它是一个非常小的图片,它应该被夹在左上角,如果它太大我希望不显示溢出。如果图像太大,让我们举个例子。我的目标是:

enter image description here

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

enter image description here

我该如何解决这个问题?

编辑

这就是我现在有多远:jsfiddle .如您所见,图像不是从左上角开始的,溢出也没有隐藏。

最佳答案

您想要的行为应该是 div 中背景图像的默认行为。所以你应该只需要 backround-image 和 background-repeat 属性。

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

关于css - 如何在不拉伸(stretch)或固定图像的情况下将图像保留在 div 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32208341/

相关文章:

html - 如何有条件地突出显示 Angular Material 表行?

用于内容对齐的 CSS

javascript - 单击更改 div id 属性

具有各种不错功能的 CSS 编辑器/GUI/应用程序

html - 使用 CSS/HTML 使点击事件一次性工作的方法

java - 如何使用 css 在 javafx 中为文本设置动画?

html - 将文本定位在文本之上

javascript - 当鼠标悬停在选项上时,如何将 SELECT <OPTION> 标记的背景颜色从蓝色更改为灰色?

html - 无法将 CSS 文件链接到 HTML?

css - 如何在页面中创建一个内容适合屏幕的 div,而不管内容的宽度如何