Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the background image show up without specific width and height?

Tags:

html

css

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;
}
like image 804
Kristina Bressler Avatar asked Aug 24 '15 05:08

Kristina Bressler


People also ask

What will happen if width and height of the image is not specified?

If width and height are not specified, the page will flicker while the image loads.

How do I make the background image fit my screen size?

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.

How do I make an image fit my background in HTML?

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.


2 Answers

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.

like image 171
Justinas Avatar answered Oct 11 '22 02:10

Justinas


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....

like image 32
Kristina Bressler Avatar answered Oct 11 '22 03:10

Kristina Bressler