将背景图片添加到<div>元素

196

我能否将背景图片添加到一个 <div> 元素中呢?如果可以的话,应该如何操作?

9个回答

231
你是指这个吗?
<style type="text/css">
.bgimg {
    background-image: url('../images/divbg.png');
}
</style>

...

<div class="bgimg">
    div with background
</div>

我可以将其设置为不可重复吗? - Valentino Ru
12
是的:background-repeat: no-repeat; http://www.w3schools.com/cssref/pr_background-repeat.asp翻译:将背景重复的方式设定为“不重复”,该属性在CSS中使用,具体信息可参考链接http://www.w3schools.com/cssref/pr_background-repeat.asp。 - Matt Becker

47

你可以使用CSS的 background 属性来实现这个功能。有几种方法可以做到:


通过ID

HTML: <div id="div-with-bg"></div>

CSS:

#div-with-bg
{
    background: color url('path') others;
}

按类别分类

HTML: <div class="div-with-bg"></div>

CSS:

.div-with-bg
{
    background: color url('path') others;
}

在 HTML 中(它很邪恶)

HTML: <div style="background: color url('path')"></div>


其中

  • color 是十六进制颜色或X11颜色中的一种
  • path 是图片路径
  • 其他,比如位置、附着方式等

background CSS 属性是以下语法中所有背景属性的连接:

backgroundbackground-color background-image background-repeat background-attachment background-position

来源:w3schools


我想使用HTML方法,但仅使用该方法是否可以添加两个位置不同的图像。我知道可以这样做:background-image: url("image.jpg"), url("image2"); 但是这样做,两个图像将在同一位置,有点“重叠”,而我想为它们设置不同的位置。 - PaulP1

36

是的:

<div style="background-image: url(../images/image.gif); height: 400px; width: 400px;">Text here</div>

26

使用此样式来获得无重复的居中背景图片。

.bgImgCenter{
    background-image: url('imagePath');
    background-repeat: no-repeat;
    background-position: center; 
    position: relative;
}

在HTML中,为您的div设置这个样式:

<div class="bgImgCenter"></div>

11

使用方法如下..

<div style="background-image: url(../images/test-background.gif); height: 200px; width: 400px; border: 1px solid black;">Example of a DIV element with a background image:</div>
<div style="background-image: url(../images/test-background.gif); height: 200px; width: 400px; border: 1px solid black;"> </div>

路径应该用单引号括起来吧? - Shane G

10
你可以简单地添加带有id的img src属性:
<body>
<img id="backgroundimage" src="bgimage.jpg" border="0" alt="">
</body>

在你的CSS文件中(拉伸背景):

#backgroundimage
{
   height: auto;
   left: 0;
   margin: 0;
   min-height: 100%;
   min-width: 674px;
   padding: 0;
   position: fixed;
   top: 0;
   width: 100%;
   z-index: -1;
}

2
这个问题是关于向 div 添加背景元素,而不是添加单独的 img 属性,因此这并不能回答这个问题。 - Dipen Shah
7
虽然这个解决方案并没有恰当地回答问题,但它让我想到了另一个我正在面对的问题,所以我要感谢它。 - Striker

6
<div class="foo">Foo Bar</div>

在你的CSS文件中:

.foo {
    background-image: url("images/foo.png");
}

2
<div id="image">Example to have Background Image</div>

我们需要将以下内容添加到样式标签中:
.image {
  background-image: url('C:\Users\ajai\Desktop\10.jpg');
}

1
你的本地路径:C:\Users\ajai\Desktop\10.jpg 不会在线上工作 ;) - Brad Ahrens
1
仅供参考,我提供这个路径。 - Guvaliour

0
大多数情况下,该方法与设置整个主体相同。
.divi{
    background-image: url('path');
}

</style>

<div class="divi"></div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接