为什么不显示背景图像没有特定的宽度和高度? [英] Why doesn't the background image show up without specific width and height?

查看:124
本文介绍了为什么不显示背景图像没有特定的宽度和高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个示例代码



我一直在想,为什么 background-image 不显示除非我以像素为单位指定图像的宽度和高度。我试图只以百分比的宽度,但它没有工作。 w3cschools.com 能够显示背景图片没有指定宽度和高度,但它仅在身体背景中起作用。任何解释或解决方案的变通方法?

HTML

 < div class = PIC >< / DIV> 

CSS

  .pic {
background:url(http://i.imgur.com/HIt6f8r.png)no-repeat;
display:block;
职位:亲属;
width:244px;
height:230px;
background-size:包含;
}


解决方案

指定高度,感谢 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;
职位:亲属;
width:20%;
height:0;
padding-bottom:20%;
background-size:100%;



$ b $ p
$ b

假设它是一个正方形,你需要做的就是匹配 padding-bottom 改为宽度



更新:
我还听说过另一个可能有用的解决方案。 http://www.mademyday.de/css- height-equal-width-with-pure-css.html



CSS

  .pic {
position:relative;
宽度:50%;
}
.pic:之前{
content:;
display:block;
padding-top:100%;
}

虽然我还没有测试过......


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;
}

解决方案

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

这篇关于为什么不显示背景图像没有特定的宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆