【问题标题】:Css image just fit with certain widthCss图像恰好适合一定的宽度
【发布时间】:2020-05-05 01:17:15
【问题描述】:

我想将图像与父级 div(图像容器)正确比例

.image-container{

height: 195px;
    border-radius: 10px;
    position: relative;
    width: 482px;
    width: 482px;
    
    }
    
    img{
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    object-fit: contain;
overflow:hidden
    }
    
    .gray-layer{
    width: 482px;
    height: 195px;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: rgba(0, 0, 0, 0.4);
    position: absolute;
    top: 0;
    }
<div class="image-container">
<img src="https://javadeveloperzone.com/wp-content/uploads/2019/02/JAVA-PARSE-LARGE-JSON-FILE-GSON-EXAMPLE-1024x488.png">
<div class="gray-layer">
</div>
</div>

我上面的代码不适合图像。请帮帮我

【问题讨论】:

  • 请澄清:您是否希望.image-container 根据图像尺寸调整其大小,或者您是否希望缩放图像以使其完全填充 div(当保留纵横比,可能意味着会有部分图像被截掉)?
  • 或者您可能希望图像采用父级的宽度,可能在垂直方向上留下空白空间?如果是这样,您希望图像在容器的顶部、中心还是底部对齐?
  • 这能回答你的问题吗? Change image size via parent DIV
  • 我只需要通过宽度和刚刚隐藏的图像的溢出来适应,但是宽度:100% 正好适合高度

标签: html css


【解决方案1】:

是的。添加缺少的结束 div 并将高度/宽度设置为 100% 以使其正常工作。

.image-container {
  height: 195px;
  border-radius: 10px;
  position: relative;
  width: 482px;
}

img {
  height: 100%;
  width: 100%;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.gray-layer {
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
}
<div class="image-container">
  <img src="https://javadeveloperzone.com/wp-content/uploads/2019/02/JAVA-PARSE-LARGE-JSON-FILE-GSON-EXAMPLE-1024x488.png">
  <div class="gray-layer"></div>
</div>

【讨论】:

  • 这不会保留图像的纵横比,除非父 div 的大小适合完美的比例。我相信您甚至可以在这里看到图像有些拉伸。
  • 刚刚隐藏的高度图像的宽度和溢出是否有解决方案?
【解决方案2】:

首先,您可以在父div 上使用overflow: hidden,以便为包含的img 使用圆角,而无需再次指定它们。

然后,如果您希望img 始终填写父div 的全部内容,则应将widthheight 设置为100% 并使用object-fit: cover

.image-container {
  width: 482px;
  height: 195px;
  position: relative;
  border-radius: 10px;
  border: 1px dashed #ccc;
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="image-container">
  <img src="https://javadeveloperzone.com/wp-content/uploads/2019/02/JAVA-PARSE-LARGE-JSON-FILE-GSON-EXAMPLE-1024x488.png">
</div>

但是,如果您希望图像仅采用父级的宽度(可能会增长或在底部留出空间),那么将 width 设置为 100% 应该可以解决问题:

.image-container {
  width: 482px;
  height: 195px;
  position: relative;
  border-radius: 10px;
  border: 1px dashed #ccc;
  overflow: hidden;
}

img {
  width: 100%;
}
<div class="image-container">
  <img src="https://javadeveloperzone.com/wp-content/uploads/2019/02/JAVA-PARSE-LARGE-JSON-FILE-GSON-EXAMPLE-1024x488.png">
</div>

请注意,为简洁起见,我省略了 .gray-layer,并为 image-container 添加了边框,以便更好地了解发生了什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2014-04-11
    • 2016-01-27
    • 1970-01-01
    • 2021-07-31
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多