背景图像位置,居中不起作用

4

我试图创建一个带有居中背景图片的页面,使用的是position center center。但是图片看起来似乎在垂直方向上超出了页面顶部,而没有水平居中。我在哪里或为什么出错了?

<!DOCTYPE html>
<html>
<style>
body
{
background-image:url('tumbleweed.jpg');
background-repeat:no-repeat;
background-position:center center;
background-color:#EAEAEA;
}
</style>
</html>

这里似乎工作正常 http://jsfiddle.net/rtw7h3ys/ - Akshay
5个回答

6
你会看到像下面这张图片一样的屏幕吗?

enter image description here

body{
  background-image:url(../IMG/BG/pizzaBackground.jpg);
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

我觉得这是因为你没有声明“height”。 添加“height:100vh”样式。
body{
  height: 100vh;    /* ADD STYLE ! */
  background-image:url(../IMG/BG/pizzaBackground.jpg);
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

将高度设置为100vh的原因是目标是body标签。

如果是其他标签,请使用不同的值。

然后这将是:

enter image description here

并添加'margin:0px'样式以去除滚动条。
body{
  margin: 0px;     /* ADD STYLE ! */
  height: 100vh;
  background-image:url(../IMG/BG/pizzaBackground.jpg);
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

然后你可以看到

enter image description here


谢谢!


2
您可以使用封面
background-image:url('tumbleweed.jpg');
-webkit-background-size: cover;
-moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;

http://jsfiddle.net/ou10gmfd/


2
尝试这个:
background-position: 50% 50%;
或者你可以在第一个 center 前加一个空格(可能会有问题)。

这完全是错误的。在第一个值前面加空格不是问题。 - Mario

0

很可能是因为您的图像太大了,请使用background-size: cover;来覆盖整个页面的背景


-2

从您的页面中删除DOCTYPE html,它就可以正常工作。 或者使用background-attachment: fixed;。那么您就不必删除DOCTYPE html了


当页面上没有DOCTYPE声明时,浏览器可能会自动进入Quirks或Strict模式。请参见https://dev59.com/PmAg5IYBdhLWcg3wwdLA以获取更多信息。 - kplus

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