Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...