可以在div中居中显示背景图像吗?我几乎什么都试过了--但没有成功:
<div id="doit">
Lorem Ipsum ...
</div>
//CSS
#doit { background-image: url(images/pic.png); background-repeat: none; text-align: center; }
这个是可能的吗?
发布于 2011-02-18 18:39:12
#doit {
background: url(url) no-repeat center;
}
发布于 2011-02-18 18:36:45
使用背景位置:
background-position: 50% 50%;
发布于 2017-03-17 23:44:04
对于居中或定位背景图像,您应该使用background-position
属性。background-position属性从元素的top
和left
侧设置背景图像的起始位置。CSS语法是background-position : xvalue yvalue;
。
"xvalue“和"yvalue”支持的值是长度单位,如px
,百分比和方向名称,如left,right等。
"xvalue“是背景的水平位置,从元素的顶部开始。这意味着如果你使用50px
,它将是"50px“远离元素的顶部。"yvalue“是具有相同条件的垂直位置。
因此,如果你使用background-position: center;
,你的背景图像将居中。
但我总是使用下面的代码:
.yourclass {
background: url(image.png) no-repeat center /cover;
}
我知道这很让人困惑,但这意味着:
.yourclass {
background-image: url(image.png);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
我也知道background-size
是一个新的属性,在压缩代码中什么是/cover
,但这些代码意味着fill
背景的大小和在windows桌面背景中的定位。
您可以在here中查看有关background-position
的更多详细信息,在here中查看有关background-size
的更多详细信息。
https://stackoverflow.com/questions/5040232
复制相似问题