使用 CSS 将背景图像居中

我想要居中的背景图像。没有使用 div,这是 CSS风格:

body{
background-position:center;
background-image:url(../images/images2.jpg) no-repeat;
}

上面的 CSS 贴片到处都是,并且居中显示,但是有一半的图片看不到,它只是向上移动。我要做的是将图像居中。即使在21英寸的屏幕上,我也可以采用这个图像来观看吗?

404040 次浏览

试试看

background-position: center center;
background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;

应该可以。

如果没有,为什么不使一个与图像的 div和使用 z-index使它的背景?这将是更容易中心比背景图像的身体。

除此之外:

或者我认为你可以使用50% ,如果你已经把你的身体 min-height到100% 。

body{


background-repeat:no-repeat;
background-position: center center;
background-image:url(../images/images2.jpg);
color:#FFF;
font-family:Arial, Helvetica, sans-serif;
min-height:100%;
}

您的代码中有一个错误。您正在使用背景图像属性的完整语法和速记符号的混合。这导致无重复被忽略,因为它不是背景图像属性的有效值。

body{
background-position:center;
background-image:url(../images/images2.jpg) no-repeat;
}

应成为下列情况之一:

body{
background:url(../images/images2.jpg) center center no-repeat;
}

或者

body
{
background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;
}

编辑: 对于您的图像“缩放”问题,您可能需要查看 这个问题的答案

我用这个代码,效果很好

html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
background: black url(back2.png) center center no-repeat;;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

试试这个 background-position: center top;

这个对你有用。

我认为 这个是人们想要的:

body
{
background-image:url('smiley.gif');
background-repeat:no-repeat;
background-attachment:fixed;
background-position:center;
}
background-repeat:no-repeat;
background-position:center center;

使用 html 4.01‘ STRICT’文档类型时,不会垂直居中显示背景图像。

添加:

background-attachment: fixed;

应该能解决问题

(所以亚历山大是对的)

如果你对上面的答案不满意,请使用这个

    * {margin: 0;padding: 0;}


html
{
height: 100%;
}


body
{
background-image: url("background.png");
background-repeat: no-repeat;
background-position: center center;
background-size: 80%;
}

唯一对我有用的就是。

margin: 0 auto

有同样的问题。使用显示和页边距属性,它工作。

.background-image {
background: url('yourimage.jpg') no-repeat;
display: block;
margin-left: auto;
margin-right: auto;
height: whateveryouwantpx;
width: whateveryouwantpx;
}

简单地替换

background-image:url(../images/images2.jpg) no-repeat;

background:url(../images/images2.jpg)  center;

像这样:

background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dore_woodcut_Divine_Comedy_01.jpg/481px-Dore_woodcut_Divine_Comedy_01.jpg);
background-repeat:no-repeat;
background-position: center;
background-size: cover;

html{
height:100%
}


body{
background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dore_woodcut_Divine_Comedy_01.jpg/481px-Dore_woodcut_Divine_Comedy_01.jpg);
background-repeat:no-repeat;
background-position: center;
background-size: cover;
}

background-position: center center;

对我来说没有..。

background-attachment: fixed;

将我的图像放在 x 轴和 y 轴的中心

background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;