Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...