我有一个将大小改变为窗口大小的背景图像,我需要在其上放置一个元素,以便它总是在相对于背景图像的相同位置.
怎么样!?
CSS
- background:url("http://placehold.it/100x100") no-repeat center center fixed;
- -webkit-background-size:"cover";
- -moz-background-size:"cover";
- -o-background-size:"cover";
- background-size:"cover";
背景图像覆盖整个背景,并通过窗口更改大小,但通过具有某些重叠来保持比例.
EDIT – 2016
我用纯CSS解决这个问题是将元素放在中间,然后使用calc函数正确地偏移它.然后调整相应的大小我使用vmin值:
- $offset-top: ...;
- $offset-left: ...;
- .element {
- top: 50%;
- left: 50%;
- transform: translate(calc(-50% + #{$offset-top}),calc(-50% + #{$offset-top}));
- width: 50vim;
- height: 50vim;
- }
解决方法
你所要求的并不是一件简单的事情,它基本上包括弄清楚background-size:cover的作用,然后使用JavaScript定位你的元素.由于背景大小的性质:覆盖图像如何流出x轴或y轴,这不能用CSS完成.
这是我解决问题的方法,在加载和调整大小时,它计算图像的尺度和x或y偏移量,并将指针绘制在相关位置.
jsFiddle (red dot in Google’s red ‘o’)
HTML
- <div id="pointer"></div>
CSS
- body {
- background:url(https://www.google.com.au/images/srpr/logo4w.png) no-repeat center center fixed;
- -webkit-background-size:cover;
- -moz-background-size:cover;
- -o-background-size:cover;
- background-size:cover;
- }
- #pointer {
- margin-left:-10px;
- margin-top:-10px;
- width:20px;
- height:20px;
- background-color:#F00;
- position:fixed;
- }
JS
- var image = { width: 550,height: 190 };
- var target = { x: 184,y: 88 };
- var pointer = $('#pointer');
- $(document).ready(updatePointer);
- $(window).resize(updatePointer);
- function updatePointer() {
- var windowWidth = $(window).width();
- var windowHeight = $(window).height();
- // Get largest dimension increase
- var xScale = windowWidth / image.width;
- var yScale = windowHeight / image.height;
- var scale;
- var yOffset = 0;
- var xOffset = 0;
- if (xScale > yScale) {
- // The image fits perfectly in x axis,stretched in y
- scale = xScale;
- yOffset = (windowHeight - (image.height * scale)) / 2;
- } else {
- // The image fits perfectly in y axis,stretched in x
- scale = yScale;
- xOffset = (windowWidth - (image.width * scale)) / 2;
- }
- pointer.css('top',(target.y) * scale + yOffset);
- pointer.css('left',(target.x) * scale + xOffset);
- }