我目前正在研究 CSS 渐变和位置,我设法做我想做的事,但幸运的是,我想了解这一切实际上是如何工作的。
例如,这是法国国旗 (merci):
.serge_testDraw {
width: 10rem;
height: 10rem;
border: 0.2rem solid black;
background-image:
linear-gradient(to right, blue 0%, blue 100%)
, linear-gradient(to right, white 0%, white 100%)
, linear-gradient(to right, red 0%, red 100%)
;
background-size: calc(100% / 3) 100%;
background-repeat: no-repeat;
background-position: 0%, 50%, 100%;
}
为什么背景位置是0%、50%、100%,而不是0、33.33%(三分之一)、66.66%(三分之二)?
另外,我不知道如何放置大小为 100% 的背景。
background-position
的百分比值不会相对于背景定位区域定位背景图像的原点。它定位整个图像。这意味着图像本身的尺寸也被考虑在内(在使用 background-size
调整它的大小之后)。
100% 100%
的背景位置类似于 right bottom
,定位图像使得图像的右下角接触到右下角背景区域。同样,50% 50%
类似于 center center
,将图像的中点放在背景区域的中点上。
想象一下,在矩形框架的内部滑动一个矩形瓷砖;将它一直向右移动(即 100%)意味着让它的右边缘接触框架的右侧(因为你不能将它滑动通过框架),并将它移动到bottom 意味着它的底部边缘接触框架的底部。
一般来说,对于任何background-position: x y
,其中两个值都是百分比,图像的x点与背景区域的x点对齐,而y点图像与背景区域的 y 点对齐。
CSS2.1的描述读起来很痛苦,所以我会引用 CSS3 Backgrounds and Borders相反,甚至还有一个图形示例:
For example, with a value pair of ‘0% 0%’, the upper left corner of the image is aligned with the upper left corner of, usually, the box's padding edge. A value pair of ‘100% 100%’ places the lower right corner of the image in the lower right corner of the area. With a value pair of ‘75% 50%’, the point 75% across and 50% down the image is to be placed at the point 75% across and 50% down the area.
但是,如果您像我一样,并且不擅长实时可视化,那么只需考虑一个滑动拼图即可。
请注意,这些都不适用于绝对值;绝对值确实定位了图像的原点。但是,如果您将绝对值锚定到右侧和/或底部,则可以更改引用点,例如 right 10px bottom 10px
将背景图像定位在距右下角 10 像素的位置背景区域。
如果您想要放置一个大小为背景区域 100% 的背景图像,您将无法使用百分比,因为您无法移动完全适合其框架的图 block (顺便说一下,这会使对于最无聊的谜题或完美的恶作剧)。无论背景图像的固有尺寸与元素的尺寸相匹配,还是您明确设置 background-size: 100%
,这都适用。因此,要定位图像,您需要使用绝对值(完全放弃滑动拼图类比)。