我有一个背景图片设置为居中并需要固定位置。但是我想将其向离中心100像素的方向移动,有什么想法吗?
CSS background: url(styles/images/bg.png) no-repeat center -100px; background-attachment: fixed;
我有一个背景图片设置为居中并需要固定位置。但是我想将其向离中心100像素的方向移动,有什么想法吗?
CSS background: url(styles/images/bg.png) no-repeat center -100px; background-attachment: fixed;
您可以通过将背景位置设置在距离左侧或右侧约50%的位置来实现此操作。如果您需要它距离中心特定像素数的左/右侧,则需要使用calc()
添加不同单位的偏移量。例如,如果您希望将背景向左移动100像素,则需要使用background-position: left calc(50% - 100px)
。请特别注意括号内的间距,因为它们是必需的。如果您希望背景图像的边缘与中心线之间有100像素的距离,则还需要减去背景图像宽度的一半。
background-position
设置为以下内容:calc(7.5% - var(--image-width) * 0.925)
(将var(--image-width)
替换为以像素为单位的背景图像宽度,0.925是1和7.5%的小数表示之间的差异,或1-0.075
)。:root {
/* Informational: */
--background-width: 100px;
}
.div2 {
width: 300px;
}
.div3 {
width: 90%;
}
.background {
/* Using multiple backgrounds, labeled below */
background-position: top left calc(50% - var(--background-width) / 2),
top left calc(50% - var(--background-width) / 2 - 150px),
top left calc(5% - var(--background-width) * 0.95);
/* Line 1: Position 50% over, then subtract half the background
width (100px / 2) to shift background edge from center */
/* Line 2: Center, then subtract half the background width (100px / 2),
then subtract half the element width (300px / 2) to shift
150 pixels from background edge to center */
/* Line 3: Position 5% over, then 5% the background width (100px * 0.95)
to shift background edge from 5% mark */
}
/* EVERYTHING BELOW CAN BE IGNORED. Scenario setup: */
div div {
box-sizing: border-box;
margin: 10px auto;
border: 1px solid black;
height: 30px;
text-align: center;
}
.div1 div {
margin: 0;
display: inline-block;
width: 50%;
border: none;
}
.div1 .left {
text-align: right;
}
.div1 .right {
text-align: left;
border-left: 1px solid black;
}
.background {
margin: 0 40px;
/* Emulates background image examples: */
background-image: linear-gradient(#f77 30px, transparent 30px),
linear-gradient(transparent 40px, #3d3 40px, #3d3 70px, transparent 70px),
linear-gradient(transparent 80px, #77f 80px);
background-repeat: no-repeat;
background-size: var(--background-width) auto;
}
All colored background boxes are applied from the parent element:
<div class="background">
<div class="div1">
<div class="left">Center </div><div class="right"> Line</div>
</div>
<div class="div2">300px wide</div>
<div class="div3">90% wide</div>
</div>
看起来你需要的是 background-position
。
查看此link以获取更多详细信息。