Why doesn't the background image show up without specific width and height?
Your <div>
element don't have any content, so the <div>
height is 0px.
The width of the <div>
is still 100%.
If you add any content to the div it will have some height and it will show a portion of image.
<body>
by default has the height of the window, so you can see the background-image.
I found a great alternative without specifying the height, thanks to http://blog.brianjohnsondesign.com/maintain-aspect-ratio-for-html-element-using-only-css-in-a-responsive-design/. HTML
<div class="pic"></div>
.pic {
background: url("http://i.imgur.com/HIt6f8r.png") no-repeat;
display: block;
position: relative;
width: 20%;
height: 0;
padding-bottom: 20%;
background-size: 100%;
}
All you need to do, assuming that it's a square, to match the padding-bottom to the width in css.
Update: I also heard about another solution that may be useful. http://www.mademyday.de/css-height-equals-width-with-pure-css.html
.pic {
position: relative;
width: 50%;
}
.pic:before {
content: "";
display: block;
padding-top: 100%;
}
although I haven't tested it out yet....
<div class="pic"></div>
Div is container, it expects to have inner elements, when it's empty you must explicitly define height.