位置元素在背景图像上.但是BG img用窗口改变大小. CSS

前端之家收集整理的这篇文章主要介绍了位置元素在背景图像上.但是BG img用窗口改变大小. CSS前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个将大小改变为窗口大小的背景图像,我需要在其上放置一个元素,以便它总是在相对于背景图像的相同位置.

怎么样!?

CSS

  1. background:url("http://placehold.it/100x100") no-repeat center center fixed;
  2. -webkit-background-size:"cover";
  3. -moz-background-size:"cover";
  4. -o-background-size:"cover";
  5. background-size:"cover";

背景图像覆盖整个背景,并通过窗口更改大小,但通过具有某些重叠来保持比例.

EDIT – 2016

我用纯CSS解决这个问题是将元素放在中间,然后使用calc函数正确地偏移它.然后调整相应的大小我使用vmin值:

  1. $offset-top: ...;
  2. $offset-left: ...;
  3.  
  4. .element {
  5. top: 50%;
  6. left: 50%;
  7. transform: translate(calc(-50% + #{$offset-top}),calc(-50% + #{$offset-top}));
  8. width: 50vim;
  9. height: 50vim;
  10. }

解决方法

你所要求的并不是一件简单的事情,它基本上包括弄清楚background-size:cover的作用,然后使用JavaScript定位你的元素.由于背景大小的性质:覆盖图像如何流出x轴或y轴,这不能用CSS完成.

这是我解决问题的方法,在加载和调整大小时,它计算图像的尺度和x或y偏移量,并将指针绘制在相关位置.

jsFiddle (red dot in Google’s red ‘o’)

HTML

  1. <div id="pointer"></div>

CSS

  1. body {
  2. background:url(https://www.google.com.au/images/srpr/logo4w.png) no-repeat center center fixed;
  3. -webkit-background-size:cover;
  4. -moz-background-size:cover;
  5. -o-background-size:cover;
  6. background-size:cover;
  7. }
  8.  
  9. #pointer {
  10. margin-left:-10px;
  11. margin-top:-10px;
  12. width:20px;
  13. height:20px;
  14. background-color:#F00;
  15. position:fixed;
  16. }

JS

  1. var image = { width: 550,height: 190 };
  2. var target = { x: 184,y: 88 };
  3.  
  4. var pointer = $('#pointer');
  5.  
  6. $(document).ready(updatePointer);
  7. $(window).resize(updatePointer);
  8.  
  9. function updatePointer() {
  10. var windowWidth = $(window).width();
  11. var windowHeight = $(window).height();
  12.  
  13. // Get largest dimension increase
  14. var xScale = windowWidth / image.width;
  15. var yScale = windowHeight / image.height;
  16. var scale;
  17. var yOffset = 0;
  18. var xOffset = 0;
  19.  
  20. if (xScale > yScale) {
  21. // The image fits perfectly in x axis,stretched in y
  22. scale = xScale;
  23. yOffset = (windowHeight - (image.height * scale)) / 2;
  24. } else {
  25. // The image fits perfectly in y axis,stretched in x
  26. scale = yScale;
  27. xOffset = (windowWidth - (image.width * scale)) / 2;
  28. }
  29.  
  30. pointer.css('top',(target.y) * scale + yOffset);
  31. pointer.css('left',(target.x) * scale + xOffset);
  32. }

猜你在找的HTML相关文章