将<div>的高度更改为背景图像的高度</div>

时间:2013-04-08 05:20:37

标签: html css twitter-bootstrap

我有两个div:

<div class="iphonebackground">
  <div class="screenbackground"></div>
</div>

.iphonebackground {
    background-image:url("../img/iphone-frame.png");
    background-repeat: no-repeat;
    background-position: center;
    background-size: 100%;
    height:576px;
}

.screenbackground {
    background-image:url("../img/iphone-background.png");
    background-repeat: no-repeat;
    background-position: center;
    background-size:100%;
    height:576px;
}

首先,iphonebackground将背景图像设置为iPhone框架的图像(http://chpwn.com/apps/iphone-frame.png)。第二个,screenbackground将背景图像设置为相同大小的PNG图像,其中包含iPhone屏幕上的图像(https://dl.dropbox.com/u/290586/iphone-bg.png)。

结果是页面呈现如下内容:http://imgur.com/yVF9gyg。由于我的网站基于Twitter Bootstrap,div的大小调整以适应浏览器窗口,所以在较小的显示器上它看起来像这样:http://imgur.com/Q2Qy4wn

如您所见,div的高度固定为576px。这意味着在第二个图像中,背景图像上方和下方有一个大的空白区域。有没有办法设置div的高度,使它们与背景图像的高度一样高,从而删除空格?

3 个答案:

答案 0 :(得分:1)

背景图像对其所附着的DIV的大小没有影响。 DIV的大小将由其内容决定,如果在CSS中明确设置,则由宽度和高度确定。

如果您的DIV宽度为%(即未知像素宽度),那么您无法根据此未知宽度设置高度而无需借助JavaScript,或者......新的CSS calc()函数,您可以将高度指定为未知宽度的比率,并让浏览器将其工作。有关详情,请参阅https://developer.mozilla.org/en-US/docs/Web/CSS/calc

支持越来越好(根据caniuse.com,这是78%),但你不能依赖它。

[edit]在我自己寻找解决方案时,我发现了一个优秀的黑客使用填充顶部,由用户Hasanavi编写,以回答this question [/ edit]

答案 1 :(得分:-1)

您可以尝试在div上使用line-height css属性。

line-height: normal; 
line-height: 3.5;    /* <number> values */
line-height: 3em;    /* <length> values */
line-height: 34%;    /* <percentage values */
line-height: 50px;   /* <Pixel> values */

line-height: inherit

希望这会有所帮助......

答案 2 :(得分:-1)

您可以使用

height:auto; in both
相关问题