CSS背景位置50%50%不起作用

时间:2016-07-16 10:38:46

标签: html css css3

有一个元素,宽度和高度未知。我想在CSS中创建一个重复的背景,并从元素的中心开始。它应该是这样的:

我的代码是:

body {
    background: url('http://www.lighthouse3d.com/wp-content/uploads/2011/03/crate.jpg') 50% 50% / 100% 100% repeat;
}

https://jsfiddle.net/5omLL24d/

3 个答案:

答案 0 :(得分:1)

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

body {
    background: url('http://www.lighthouse3d.com/wp-content/uploads/2011/03/crate.jpg');
    background-repeat: repeat;
    background-position: center center;
}

JSFiddle

UPDATED(中心角落,webkit) 谢谢,CBroe和Lovelock

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

body {
    background: url('http://www.lighthouse3d.com/wp-content/uploads/2011/03/crate.jpg');
    background-repeat: repeat;
    background-position: -webkit-calc(50% + 128px) -webkit-calc(50% + 128px); // 128 pixels is half of the background image
    background-position: calc(50% + 128px) calc(50% + 128px); // 128 pixels is half of the background image
}

JSFiddle

答案 1 :(得分:0)

无需添加额外的css属性。你会直接用这种方式

body {
    background: url('http://www.lighthouse3d.com/wp-content/uploads/2011/03/crate.jpg');
}

答案 2 :(得分:-1)

试试这个:

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

body {
    background: url('http://www.lighthouse3d.com/wp-content/uploads/2011/03/crate.jpg');

    background-position: center;
}

DEMO HERE