全面显示背景图片

时间:2019-06-16 13:12:59

标签: css

我正在建立一个网站,并想创建一个响应式背景图片,但是我只得到一行背景图片。我需要使用什么属性来使整个背景图像适合?

我创建了2个文件, index.html:

<div id="logo">Test</div>

style.css:

#logo {
background-image: url("bg.png");
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}

我尝试了很多次,但是只有一行获得了背景图像。我希望背景图片能完全显示在屏幕上,而不必使用height属性,我认为这会使网站的响应速度降低。

2 个答案:

答案 0 :(得分:0)

如果您希望图像具有与屏幕相同的高度,则可以使用height:100vh。但是,如果您只想要完整尺寸的图像,则可以这样操作:

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#image{
max-height: 100%;
    max-width: 100%;
}

#text{
  position: absolute;
  color: white;
  top: 0
}
<img id="image" src="https://images.unsplash.com/photo-1528920304568-7aa06b3dda8b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80">
<div id="text">test</div>

答案 1 :(得分:0)

您应该更改徽标div的高度,并通过为正文和徽标div添加height:100%来将其设置为全高,您的代码应类似于以下代码

html, body
{
   height: 100%;
}
#logo {
   background-image: url("bg.png");
   background-position: center center;
   background-repeat: no-repeat;
   background-attachment: fixed;
   background-size: cover;
   height:100%;
}