【问题标题】:CSS How do you fit images of different aspect ratios and different sizes in a 3:1 rectangle div?CSS 你如何在一个 3:1 的矩形 div 中放置不同纵横比和不同大小的图像?
【发布时间】:2021-09-20 15:12:59
【问题描述】:

根据维基百科https://commons.wikimedia.org/wiki/File:Standard_web_banner_ad_sizes.svg,横幅 div (className content-area-container) 是一个 3:1 的 300x100 尺寸矩形

但是,它使用vw 单位,因此它会随着网页视口最大化或最小化而按比例增长和缩小

该 div 必须包含 1 个徽标图片。徽标图像具有各种尺寸和纵横比。大多数是长方形的,有些是正方形的,有些很宽或很高

我的问题是,如何在不影响纵横比的情况下将图像徽标放在 div 的中心,填充并尽可能多地显示?

图片logo不能与下面的文字和内容重叠,并且不能超过banner div的最大高度,否则父div会溢出

我的 css 和 html 没有使图像徽标适合,而是仍保持原始大小

<div className="content-area">
    <div className="content-area-container">
        <img className="logo" src={`${image_logo_url_path}`} alt="boxart" />
    </div>
</div>
.content-area {
    left: 0;
    right: 0;
    height: 100%;
    z-index: 3;
  }


.content-area-container {
    padding: 18px 0 12px 4%;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
  }

  .logo {
    display:flex;
    align-items: center;
    margin-right: 5px;
  }
  
  .logo img {
    object-fit: contain;
    height: 25px;
  }

【问题讨论】:

  • 如果没有您提到的文本的完整示例,我最好的猜测是使用background-image 属性以及background-size: contain; background-repeat: no-repeat;background-position: center; 在那里设置您的图像
  • 我的意思是位于图像徽标 div 下方的其他 div 中的文本和外部内容
  • 由于 imgs 是徽标,因此始终显示整个图像非常重要,不允许对其进行裁剪或(更糟糕的)拉伸,因此请遵循 @Parco 的建议并使用 contains 来调整它们的大小。跨度>

标签: html css aspect-ratio object-fit


【解决方案1】:

似乎在封闭空间中使用简单的width:100% 就可以解决问题。

.logo-container{
border:1px solid #ccc;
padding:10px;
}

.logo-container img{
width:100%;
height:auto;
}
<div class='logo-container'>
<img src='https://picsum.photos/2000/3000' />
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多