Here\'s an example code
I\'ve been wondering why the background-image
doesn\'t show up unless I specific the image\'s width and height in pixels. I trie
If you don't specify height, the size of your div
is given by the size of its contents, i.e. it's 0x0, so you don't have much chance of seeing a background image. Add
border: 1px solid red;
to see how large your div is (or isn't).
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>
CSS
.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
CSS
.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.
Your background image will not show because the div element has no content, this means that its height is 0.
You could use this jQuery code to make your div take the size of the window.
$(function () {
'use strict';
$('.div').height($(window).height());
$(window).resize(function () {
$('.div').height($(window).height());
})
});