Dus*_*ilk 13 css position cover background-image
我有一个背景图像,它改变了窗口大小的大小,我需要在它上面放置一个元素,使它总是在相对于背景图像的相同位置.
怎么样!?
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";
Run Code Online (Sandbox Code Playgroud)
背景图像覆盖整个背景并随窗口改变大小,但通过叠加来保持比例.
编辑 - 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;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*mms 27
你所要求的并不是一件微不足道的事情,它主要涉及弄清楚如何background-size:cover
工作,然后使用JavaScript定位你的元素.由于background-size:cover
图像如何流出x轴或y轴的性质,这不能用CSS完成.
这是我对问题的解决方案,在加载和调整大小时,它会计算图像的比例和x或y偏移量,并在相关位置绘制指针.
HTML
<div id="pointer"></div>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8034 次 |
最近记录: |