【问题标题】:Image fitting in container div容器 div 中的图像拟合
【发布时间】:2017-05-09 10:38:36
【问题描述】:

我正在尝试用图像填充容器,但找不到解决方案。

如果图片太短,我需要让它们全高,但它们可能会溢出侧面。 如果图片太窄,我需要让它们全宽,但它们会溢出底部。

<div class="cb-img-fw four-image">
    <a href="postURL"><img src="imageURL"></a>
</div>

和当前的 css

.four-grid-post > .four-image{
max-height: 184px;
max-width: 271px;
overflow: hidden;
}

.four-grid-post > .four-image img{
min-width: 100%;
max-width: 100%;
height: auto;
}

我也对 jQuery 解决方案持开放态度,但我的内容使用 ajax 加载,因此可能会导致一些问题。

【问题讨论】:

标签: jquery css resize image-resizing


【解决方案1】:

您可以使用object-fitobject-position CSS3 属性。 Edge 尚不支持它们,但有 a polyfill。 见feature support on CanIUse

.four-grid-post > .four-image {
	display: inline-block;
	height: 184px;
	width: 271px;
	overflow: hidden;
	border: dashed 2px red;
}

.four-grid-post > .four-image img {
	width: 100%;
	height: 100%;
	object-fit: cover;
	object-position: top center; /* To crop from the bottom */
}
<div class="four-grid-post">
	<div class="cb-img-fw four-image">
		<a href="postURL"><img src="http://placehold.it/400x300"></a>
	</div>
	<div class="cb-img-fw four-image">
		<a href="postURL"><img src="http://placehold.it/400x200"></a>
	</div>
	<div class="cb-img-fw four-image">
		<a href="postURL"><img src="http://placehold.it/300x400"></a>
	</div>
</div>

【讨论】:

    【解决方案2】:

    我建议更改css上的imgbackground

    .four-image {
      display: block;
      border: 1px solid gray;
      width: 271px;
      margin-bottom: 1em;
    }
    
    .four-image a {
      display: block;
      width: 271px;
      height: 184px;
      background-size: cover;
      background-position: center center;
    }
    <div class="cb-img-fw four-image">
      <a href="postURL" style="background-image: url('http://placehold.it/600x200');"></a>
      600x200
    </div>
    <div class="cb-img-fw four-image">
      <a href="postURL" style="background-image: url('http://placehold.it/200x600');"></a>
      200x600
    </div>
    <div class="cb-img-fw four-image">
      <a href="postURL" style="background-image: url('http://placehold.it/600x600');"></a>
      600x600
    </div>

    【讨论】:

      【解决方案3】:

      试试这个脚本 它会将您的图像设置为背景图像 然后你可以给背景图片指定高度和宽度,并使其背景大小覆盖

      var images = $(".four-image").find("img");
       $.each(images, function (index, item) {
       var $item = $(item),
       src = $item.attr('src'),
       cont = $item.closest('.four-image').css('background-image', 'url(' + src + 
       ')');
      });    
      

      【讨论】:

        猜你喜欢
        • 2021-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-07
        • 2014-12-10
        • 2023-03-16
        • 1970-01-01
        • 2018-09-10
        相关资源
        最近更新 更多