背景位置 属性 无法使图像居中

background-position property unable to center the image

以下代码无法将图像置于屏幕中央。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            background-image: url("../images/dandelion.jpg");
            background-repeat: no-repeat;
            background-position: center center;
        }
    </style>
</head>
<body>


</body>
</html>

这就是我得到的。

你的 body 只和里面的东西一样高,所以它实际上是正确居中的。

要获得您想要的结果,您需要通过添加内容来使实际页面更长,或者解决这个问题:

html,body{ height:100%; }

请注意,您也需要在其中包含 html,因为百分比高度是相对于其父级的(在这种情况下,<html><body> 的父级)

你可能想尝试这样的事情fiddle

body{
  background-image: url("http://i.imgur.com/InDshke.png");
  background-repeat: no-repeat;
  background-position: center -25%;
  background-size: 50%;
  height: 100%;
  width:100%;
}

检查这个 Fiddle (jsFiddle)。

您需要重置默认属性并赋予这些一些样式,因为您的容器 <html><body> 会根据其中的内容(在本例中为图像)进行调整。

应用这些样式:

html, body {
  width: 100%;
  height: 100%;
}

body {
  margin: 0;
  background-image: url("http://placehold.it/200x200");
  background-repeat: no-repeat;
  background-position: center center;
}

希望对您有所帮助!

给出 html 和 body height 100% and background position 50% 50% or center center.

html {
    height: 100%;
}
body{
    background-image: url("http://i.imgur.com/InDshke.png");
    background-repeat: no-repeat;
    background-position: 50% 50%;
    height: 100%;
}