向 < div > 元素添加背景图像

有没有可能让一个 <div>元素包含一个背景图像,如果有的话,我该怎么做呢?

971278 次浏览
<div class="foo">Foo Bar</div>

并在您的 CSS 文件:

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

使用喜欢. 。

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

你是说这个吗?

<style type="text/css">
.bgimg {
background-image: url('../images/divbg.png');
}
</style>


...


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

是的 :

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

你可以使用 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>


在哪里 :

  • Color 是以十六进制表示的颜色,或者是来自于“ https://en.wikipedia.org/wiki/Web _ color # X11 _ color _ Names”rel = “ noReferrer”> X11颜色的颜色
  • Path 是图像的路径
  • 其他人喜欢位置、依恋

属性是该语法中所有背景 -xxx 规范的连接:

背景 : 背景色 背景图像背景图像 背景-重复 背景-附件 背景-位置

资料来源: W3学校

您可以简单地使用 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;
}
<div id="image">Example to have Background Image</div>

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

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

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

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

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

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

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

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


</style>


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