【问题标题】:How can I get a background image displayed behind content?如何在内容后面显示背景图像?
【发布时间】:2020-12-17 22:59:17
【问题描述】:
我正在使用 Visual Studio 创建一个聊天应用程序,并希望在主页和关于我们的页面上添加背景图像,这两个页面都已经有一个导航栏,并且主页有一个框,用户可以在其中输入详细信息和加入聊天室,我想在所有这些后面添加一张图片,我尝试使用不同的代码,但最接近的是这个:
HTML
<img src="image/friends.jpg" alt="image">
CSS
div {
background: url('image/friends.jpg');
background-size: cover;
background-position: center;
}
但是图片没有完整显示,它只是显示图片图标并删除了内容,请帮助
【问题讨论】:
标签:
css
background-image
background-position
background-size
【解决方案1】:
您做得对,但请从您的 HTML 中删除这一行。
<img src="image/friends.jpg" alt="image">
您已经为 div 提供了 CSS 中的背景图片,保留 img 标记将再次添加图片并将其添加到内容之上。
如果您希望图像成为整个页面的背景,您还应该在 body 上使用 CSS background-image。
body {
background-image: url('image/friends.jpg');
background-size: cover;
background-position: center;
}
【解决方案2】:
尝试瞄准身体本身。
在你的 CSS 中而不是这样做:
div {
background: url('image/friends.jpg');
background-size: cover;
background-position: center;
}
这样做:
body {
background: url('image/friends.jpg');
background-size: cover;
background-position: center;
}
【解决方案3】:
使用background-image css 属性。为此,无需在您的 html 中提供任何额外的 img 元素。
div.bg {
background-image: url("https://www.w3schools.com/bootstrap4/cinqueterre.jpg");
background-color: #cccccc;
background-size: cover;
background-position: center;
}
<div class="bg">
<h1>The background-image Property</h1>
<p>Hello World!</p>
</div>
【解决方案4】:
你不需要
<img src="image/friends.jpg" alt="image">
只需使用 CSS:
body {
background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366");
background-size: cover;
background-position: center; // if you want the image to be centered
}
或(见 sn-p)
.bg {
background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366");
background-size: cover;
background-position: center; // if you want the image to be centered
}
.bg {
background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366");
background-size: cover;
background-position: center;
}
div {
height: 700px;
}
<div class="bg">
I am creating a chat app with visual studio and want to add a background image on the home page and about us page, both pages already have a nav-bar and the home page has a box where the user can enter details and join the chatroom and I want to add an image behind all of that, I tried using different codes but the one that came close is this one...
</div>