【问题标题】:Make background image fill div no matter the image aspect ratio无论图像纵横比如何,都使背景图像填充 div
【发布时间】:2015-10-29 18:32:18
【问题描述】:

我想知道如何用图像填充divs 背景。无论图像的纵横比如何(横向或纵向)。我尝试使用几种方法。在background-size: cover; 到background-size: 100% 100%; 上,它并不总是填充 div。 div 具有横向宽度/高度比,图像确实具有随机比例。如果我尝试background-size: cover;,风景会填满整个背景,但肖像不会(左右两侧有间隙)。

编辑:

div { 
   background: url(img.png) no-repeat center center; 
   background-size: cover; 
   height: 100%; 
   width: 100%;
}

【问题讨论】:

  • 向我们展示您的代码。你试过背景位置:中心; ?
  • background-size:cover; 是正确的值。它总是会填充 div,但图像会被裁剪。
  • @APAD1 显然图像会被裁剪,但它对我不起作用!见上文。
  • 对我来说很好:jsfiddle.net/qqxp2vnj
  • @APAD1 给出了正确答案:一个已经存在多年的简单解决方案。

标签: html css


【解决方案1】:

你可以试试这个

div { 
   background: url(img.png) no-repeat center center; 
   background-size: contain; /*i think its better to use contain if you;re using a large png*/
   height: 100vh!important; 
   width: 100hw!important;
   overflow:visible;
}

【讨论】:

  • 我不想用图像填充整个页面。您假设这是因为 100% 高度和宽度值。但这只是因为我周围有一个父 div。
  • 嘿@RachelGallen 我同意你的回答,我想知道 100hw 是什么意思?
  • @divy3993 100 水平宽度,vh 为垂直高度
  • @RachelGallen 请参阅我在 OP 的评论。
  • 不要使用height: 100vh;和width: 100vw;,而是使用min-height: 100%;和min-width: 100%;,因为如果你使用vh(视口高度)和vw(视口宽度),图像会总是相对于视口拉伸,而不是相对于父元素拉伸,这是不受欢迎的行为。
【解决方案2】:

background-size:cover; 应该可以满足您的需求。基本上,cover 值将导致背景图像完全填充 div,无论 div 的方向或大小如何,同时保持图像的纵横比。此解决方案的一个警告是图像将被裁剪,因为它必须拉伸以填充 div。

More info on the background-size property

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2018-11-08
    • 2018-05-14
    • 1970-01-01
    • 2019-04-01
    • 2010-12-25
    相关资源
    最近更新 更多