【问题标题】:Fit div size to background image使 div 大小适合背景图像
【发布时间】:2015-07-30 22:24:57
【问题描述】:

我正在尝试设置 div 的大小(宽度和高度)以匹配它的背景图像大小,但我无法让它工作。 背景图像大小必须以百分比表示,因为我正在处理一个响应式网站。在较小的屏幕上,背景应完全显示(宽度较小,但仍成比例),并且拥有图像的 div 应遵循该尺寸。

我尝试了背景大小的各种值,例如自动 100%、覆盖、包含等,但没有任何效果。 这里有一个类似的问题:scale div to background image size 但它也没有解决我的问题。

如果有人知道怎么做,我将不胜感激。

编辑: 我做了一个小提琴来展示这种行为:http://jsfiddle.net/osv1v9re/5/ 这条线使背景图像变得如此之小:

background-size: auto 100%;

但是如果被移除了,背景会填充合适的宽度,而不是高度。

【问题讨论】:

  • 如果您能给我们您正在尝试的代码,我们愿意解决您的问题
  • 制作一个小提琴,以便我们为您提供帮助
  • <div> 标签无法适应background-image 大小,您需要使用<img> 标签并在height: auto 或javascript 之间选择div
  • 除非您知道每个断点处图像的宽度和高度,否则这是不可能的。另一种方法是将背景图像设置为覆盖在 div 上。这是一个例子。 codepen.io/pacMakaveli/pen/oXLPKd
  • 你不能有div的百分比大小和background-sizecontain吗?

标签: css responsive-design background-size


【解决方案1】:

标签无法适应背景图片大小,您需要使用标签并在 height: auto for the div 或 javascript 之间进行选择

// **** Problem ****

// Wrong html :
<div class="my_class"><div>

// with css :
.my_class {
    width: 100%;
    height: 100%;
    background-image: url(/images/my-image.jpg);
    background-size: 100%;
    background-position: center;
    background-repeat: no-repeat;
}

//****  Solution ****

// use css:
.my_class {
    width: 100%;
    height: 100%;
    background-image: url(/images/my-image.jpg);
    background-size: contain;
}

【讨论】:

    【解决方案2】:

    *{
        padding: 0;
        margin: 0;
    }
    
    
    div{
        width: 100%;
    }
    div figure{
        padding-top: 36.56%;  /* 702px/1920px = 0.3656 */
        display: block;
        background: url("https://st.fl.ru/images/landing/bg2.jpg") no-repeat center top;
        background-size: cover;  
    }
    <div>    
        <figure></figure>
    </div>

    【讨论】:

      【解决方案3】:

      您可以使用 padding-bottom 或 padding-top 来设置响应高度 因为你不能修复 '%' 中的高度属性和 '%' 中的宽度。

      div{
      
      	background-image: url(url);
      	background-repeat: no-repeat;
      	background-size: 100% 100%;
      	background-position: center;
      
      	margin: 0 auto;
      
      	width: 100%;
      	padding-bottom:  heightPicure / widthPicture + %; //do it manually or using scss rules
      
      }

      【讨论】:

        猜你喜欢
        • 2015-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-06
        • 2013-02-25
        • 2012-01-02
        • 2015-11-04
        • 2012-07-19
        相关资源
        最近更新 更多