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 tried to specific only the width in percentage but it didn't work. The w3cschools.com was able to show the background image without specifying the width and height, but it works only in body background. Any explanation or solution workaround?
HTML
<div class="pic"></div>
CSS
.pic {
background: url("http://i.imgur.com/HIt6f8r.png") no-repeat;
display: block;
position: relative;
width: 244px;
height: 230px;
background-size: contain;
}
If width and height are not specified, the page will flicker while the image loads.
Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.
Fill the Entire Viewport with the background-size Property It is possible to set the CSS background-size property to cover. Using this value, the browser will automatically and proportionally scale the background image's width and height so that they are either equal to or greater than the view port's 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>
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With