2015-08-25 72 views
0

我有这个网站:如何在div内保持图像而不伸展或压缩?

<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

其中蓝色是图像和红色股利。

enter image description here

我怎样才能解决这个问题:什么我从我上面的代码张贴是,如果图片太大以下?

编辑

,这是我现在在多大程度上是:jsfiddle。正如你所看到的,图像不是从左上角开始的,溢出没有隐藏。

+0

你能提供一个小提琴吗? – RWAM

+0

这正是你想要做的:https://www.exratione.com/2011/09/how-to-overflow-a-background-image-using-css3/ –

+0

用小提琴更新 – Mulgard

回答

0

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

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

这就是我已经有'.postcard-classic' – Mulgard

+0

是的,我所说的是从其中删除一切。 – dinomix

+0

不能这样做。它需要其他造型的东西。我用小提琴的例子发布了一个工作解决方案。 – Mulgard

0

你几乎不应该指定任何值宽度

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

忽略宽度导致相同的结果。 – Mulgard

0

我想我可以接受的解决方案住:

fiddle

.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; 
} 
0

使用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%; 
}