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


170

是否可以使一个<div>元素包含背景图像,如果是这样,我将如何去做?

Answers:



42

您可以使用CSS的background属性来做到这一点。有几种方法可以做到:


按编号

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>


哪里

  • 颜色是十六进制颜色或X11颜色中的一种
  • 路径是图像的路径
  • 其他人,例如职位,公务员

background CSS属性是该语法中所有background-xxx属性的连接:

背景背景色 背景图像 背景重复 背景附件 背景位置 ;

资料来源:w3schools


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

32

是的

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

14

使用此样式可获得居中的背景图像,而无需重复。

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

在HTML中,为您的div设置以下样式:

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

10

使用像..

<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

7

您可以简单地添加一个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

3
尽管此解决方案无法正确回答问题,但确实使我对所面临的另一个问题有了一个想法,为此,我表示感谢。
Striker


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

我们需要在样式标签中添加以下内容:

.imgg(

   background-image: url('C:\Users\ajai\Desktop\10.jpg');

)

您的本地路径:C:\ Users \ ajai \ Desktop \ 10.jpg永远不会在线工作;)
AlmostPitt

只是为了颤抖,我给了这条路
Guvaliour 19/12/14

0

在大多数情况下,该方法与设置整个身体相同

.divi{
    background-image: url('path');
}

</style>

<div class="divi"></div>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.