3

I have two div's:

<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;
}

The first, iphonebackground has background-image set as an image of an iPhone frame (http://chpwn.com/apps/iphone-frame.png). The second, screenbackground has background-image set as PNG image the same size which holds the image of what would be on the iPhone's screen (https://dl.dropbox.com/u/290586/iphone-bg.png).

The result of this is that the page renders something like this: https://i.stack.imgur.com/b4NRm.jpg. As my site is based on the Twitter Bootstrap the div's resize to fit the browser window so on a smaller display it looks something like this: https://i.stack.imgur.com/3KIKO.jpg.

As you can see, the height of the div is fixed at 576px. This means that in the second image there is a large blank space above and below the background-image. Is there a way to set the height of the divs so that they are as high as the size of the background-image's height, thus removing the blank space?

Benedict Lewis
  • 2,733
  • 7
  • 37
  • 78

3 Answers3

1

A background image has no effect on the size of the DIV to which it is attached. The size of that DIV will be determined by its content, or by width and height if explicitly set in your CSS.

If you have a DIV with a % width (i.e. unknown pixel width), then you cannot set the height based upon this unknown width without resorting to JavaScript, or... the new CSS calc() function, where you could specify the height as a ratio of the unknown width and let the browser work it out. See https://developer.mozilla.org/en-US/docs/Web/CSS/calc for more.

Support is getting better (78% according to caniuse.com) but you can't rely on it.

[edit] While looking for a solution myself, I found an excellent hack using padding-top, written by user Hasanavi in answer to this question [/edit]

Community
  • 1
  • 1
terraling
  • 470
  • 7
  • 23
-1

You can try using line-height css property on your div.

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

Hope this helps...

Phillip-juan
  • 546
  • 4
  • 29
-1

You can use

height:auto; in both
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
MR. Kumar
  • 661
  • 8
  • 25