【问题标题】:how to make the height of a background image (or an empty span) responsive?如何使背景图像(或空跨度)的高度响应?
【发布时间】:2012-06-08 22:42:21
【问题描述】:

这可能是 html 标记

<header>
   <span> <!-- background image here -->  </span>
  <hgroup>
     <h1 class="testing">CSS3 and Compass Documentation</h1>
     <h2>here I am going to document my compass and CSS3 learning</h2>
  </hgroup>
</header>​

这将是我的 css 的集市:

header span {
    background: url(banner.gif) center 0 no-repeat;
    background-size: 100% auto;
    display: block;
    height: 170px;  /* maybe this is where it needs changing*/
    width: 100%; 
}

一旦您开始缩小浏览器窗口(例如 iphone 尺寸),问题就开始了。图像缩小(如我所愿),但高度仍然保持170px,在图像和hgroup 内容之间留下更大的差距

我曾尝试使用height: 100%,但这根本不起作用(至少在这种情况下)。

如果您需要演示 http://jsfiddle.net/Jcp6H/

【问题讨论】:

    标签: css responsive-design


    【解决方案1】:

    在这种情况下,您希望 &lt;span&gt; 元素根据(背景)图像的高度调整大小。

    我建议使用&lt;img&gt; 标签而不是背景图片。

    <header>
        <img src="http://movethewebforward.org/css/img/beanie-webasaurs.gif" alt="Webasaurs!" />
        <hgroup>
            <h1 class="testing">CSS3 and Compass Documentation</h1>
            <h2>here I am going to document my compass and CSS3 learning</h2>
        </hgroup>
    </header>​
    

    ​以 CSS 样式设置您的图像:

    header {
      max-width: 950px; 
    }
    
    header img{
        display: block;
        width: 100%;
    }
    
      header h1 {
        color: #324a69;
        font-size: 3em;
        text-align: center;
        text-shadow: 1px 1px 0 white;
        position: relative; 
    }
    
      header h2 {
        clear: both;
        color: #705635;
        text-shadow: 1px 1px 0 white;
        font-size: 2em;
        text-align: center; 
    }​
    

    很难根据背景图像调整元素的高度...

    【讨论】:

    • 谢谢。但出于兴趣,是否可以“根据背景图像调整元素的高度......” - 以获得我想要的
    • 我认为不可能根据背景图像大小来调整元素的大小。然而,相反的方式(基于元素大小的背景图像大小)今天可以通过 CSS 规则“background-size:cover|contain”轻松实现。
    【解决方案2】:

    首先使用跨度内的图像,因为它更容易使用。

     <span><img src="banner.jpg" /></span>
    

    我试过这个作为例子,你可以用你需要的任何东西替换

    header span img {
    background: #960;
    display: block;
    max-height: 170px;
    max-width:950px;
    width: 100%;
    height:100%; 
    

    }

    你需要做的就是设置一个最大高度和最大宽度,这样它们就会随着浏览器缩小而不会添加额外的空格。如果需要,您还可以设置最小高度等来阻止它变得太小。

    试试看是否适合你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 2015-08-13
      • 2022-01-21
      • 1970-01-01
      • 2014-05-29
      相关资源
      最近更新 更多