background-position属性无法使图像居中

时间:2016-11-05 12:46:23

标签: html css background-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>

这就是我得到的。

enter image description here

4 个答案:

答案 0 :(得分:1)

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

要获得您想要的结果,您需要通过向其添加内容来延长实际页面的时间,或者要解决此问题:

html,body{ height:100%; }

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

答案 1 :(得分:0)

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

&#13;
&#13;
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%;
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

结帐 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;
}

希望这有帮助!

答案 3 :(得分:0)

给予html和身高100%,背景位置50%50%或居中心。

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