2014-11-12 3 views
3

background-size: cover으로 배경 이미지 위에 텍스트를 오버레이하고 싶습니다.창 크기에 관계없이 배경 이미지를 기준으로 div 오버레이를 유지하십시오.

문제는 창의 크기와 상관없이 오버레이 div를 배경 이미지와 동일한 위치에 유지하는 방법입니다.

http://jsfiddle.net/resting/2yr0b6v7/ 그래서 나는 관계없이 창 크기의, 고양이의 눈을 통해 단어 eye을 배치 할 :

여기 놀러 바이올린입니다.

CSS 또는 JS 솔루션 모두 환영합니다. 당신이 당신의 배경 이미지의 위치와 크기를 설정하는 방법에 따라

+0

는'%'시도했지만 그것은 실제로 많은 위치에서 움직입니다. 배경 이미지에 비해 div 오버레이를 사용하는 것이 불가능할 수도 있습니다. 창문에 항상 비례 해 보입니다. – Parody

+0

을주고 오히려 px''보다 그 지역 내에서 그것을 유지 할 수있는 빠른 방법은'%'를 사용하는 작은하지만 이동합니다 – resting

+0

http://jsfiddle.net/f4yovb09/1/embedded/result/ 내가 언급 한 것처럼 %를 사용하여 크기를 조정하는 것이 눈 가까이에 비교적 가까이 있는지 확인하십시오. – Parody

답변

4

편집 : 추가 JS 대안

나는이 CSS를 함께 할 거의 포기했다, 그러나 나는 새 (틱) CSS 단위 vh and vw를 기억 될 수 있음을 확신했다 ... .

jsfiddle

CSS

,451,515,
html, body{ 
    height: 100%; 
    width: 100%; 
} 
.cat { 
    height: 100%; 
    width: 100%; 
    position: relative; 
    background:url(http://placekitten.com/g/800/400) no-repeat center center/cover; 
} 
.place-on-eye { 
    position: absolute; 
    color: #fff; 
    margin:0; 
} 

@media (min-aspect-ratio: 2/1) {  
    .place-on-eye { 
     bottom: 50%; 
     left: 46.875%; 
     margin-bottom: 1.25vw; 
    } 
} 

@media (max-aspect-ratio: 2/1) { 
    .place-on-eye { 
     bottom: 52.5%; 
     left: 50%; 
     margin-left: -6.25vh; 
    } 
} 

설명

그래서 왼쪽 눈은 이미지가 중심으로되어 있기 때문에 375, 190, 그리고, 우리는 또한 얼마나 멀리 중앙 오프 알고 싶은 것입니다에서 약 10 그렇게 25이다. 이미지가 덮여 있기 때문에 뷰포트의 종횡비가 배경 이미지의 종횡비보다 크거나 작은 지 여부에 따라 이미지의 크기가 변경됩니다. 이것을 알면 미디어 쿼리를 사용하여 텍스트의 위치를 ​​지정할 수 있습니다.

이미지가 2 : 1이므로 뷰포트 종횡비가> 2 : 1 인 경우 이미지의 너비는 뷰포트의 너비이므로 <p>의 왼쪽 위치는 항상 46.867 %이어야합니다. (375/800). 이미지가 뷰포트 상단과 하단을 넘어서 확장되므로 하단 위치가 더 어려워 질 것입니다. 이미지가 중앙에 배치되어 있다는 것을 알고 있으므로 먼저 <p>을 중간으로 이동 한 다음 2 위로 밀어 올립니다.이미지 높이의 5 % (10/400). 이미지의 높이를 알 수는 없지만 이미지 종횡비를 알 수 있고 이미지의 너비가 뷰포트의 너비와 같으므로 높이의 2.5 % = 너비가 1.25 %입니다. 따라서 아래쪽을 1.25 % 너비만큼 이동해야합니다.이 값은 margin-bottom:1.25vw으로 설정하면됩니다. 덧붙여서, 패딩은 항상 너비에 상대적으로 계산되므로 padding-bottom:1.25%으로 설정할 수 있기 때문에 vw없이이 작업을 수행 할 수 있습니다. 그러나 높이를 기준으로 왼쪽을 배치해야하는 다음 경우에는 작동하지 않습니다.

종횡비가 < 2 : 1 인 경우는 유사합니다. 이미지의 높이는 뷰포트의 높이이므로 하단 위치는 항상 52.5 % (210/400)이어야하며 왼쪽은 위에서와 비슷하게 계산됩니다. 그것을 중심으로 이동 한 다음 이미지의 너비를 3.125 % (25/800)만큼 백업합니다. 이는 이미지 높이 (뷰포트 높이와 같음)가 6.25 %이므로 margin-left:-6.25vh입니다.

이 정보가 정확하고 도움이 되었기를 바랍니다.

JS 대안

jsfiddle

여기 JS를 사용하는 대안이다. forEach 및 bind와 같은 몇 가지 기능을 사용합니다. 브라우저에서 필요한 브라우저의 나이에 따라 문제가 발생할 수 있지만 쉽게 교체 할 수 있습니다. js를 사용하면 bg 이미지의 크기를 직접 계산할 수 있으므로 위치를 쉽게 지정할 수 있습니다. 여기 아니 가장 우아한 코드 만 간다 : 나는이 개 답변에서 원칙을 빌려 fiddle했을

//elem:  element that has the bg image 
//features: array of features to mark on the image 
//bgWidth: intrinsic width of background image 
//bgHeight: intrinsic height of background image 
function FeatureImage(elem, features, bgWidth, bgHeight) { 
    this.ratio = bgWidth/bgHeight; //aspect ratio of bg image 
    this.element = elem; 
    this.features = features; 
    var feature, p; 
    for (var i = 0; i < features.length; i++) { 
     feature = features[i]; 
     feature.left = feature.x/bgWidth; //percent from the left edge of bg image the feature resides 
     feature.bottom = (bgHeight - feature.y)/bgHeight; //percent from bottom edge of bg image that feature resides    
     feature.p = this.createMarker(feature.name); 
    } 
    window.addEventListener("resize", this.setFeaturePositions.bind(this)); 
    this.setFeaturePositions(); //initialize the <p> positions 
} 

FeatureImage.prototype.createMarker = function(name) { 
    var p = document.createElement("p"); //the <p> that acts as the feature marker 
    p.className = "featureTag"; 
    p.innerHTML = name; 
    this.element.appendChild(p); 
    return p 
} 

FeatureImage.prototype.setFeaturePositions = function() { 
    var eratio = this.element.clientWidth/this.element.clientHeight; //calc the current container aspect ratio 
    if (eratio > this.ratio) { // width of scaled bg image is equal to width of container 
     this.scaledHeight = this.element.clientWidth/this.ratio; // pre calc the scaled height of bg image 
     this.scaledDY = (this.scaledHeight - this.element.clientHeight)/2; // pre calc the amount of the image that is outside the bottom of the container 
     this.features.forEach(this.setWide, this); // set the position of each feature marker 
    } 
    else { // height of scaled bg image is equal to height of container 
     this.scaledWidth = this.element.clientHeight * this.ratio; // pre calc the scaled width of bg image 
     this.scaledDX = (this.scaledWidth - this.element.clientWidth)/2; // pre calc the amount of the image that is outside the left of the container 
     this.features.forEach(this.setTall, this); // set the position of each feature marker 
    } 
} 

FeatureImage.prototype.setWide = function (feature) { 
    feature.p.style.left = feature.left * this.element.clientWidth + "px"; 
    feature.p.style.bottom = this.scaledHeight * feature.bottom - this.scaledDY + "px"; // calc the pixels above the bottom edge of the image - the amount below the container 
} 

FeatureImage.prototype.setTall = function (feature) { 
    feature.p.style.bottom = feature.bottom * this.element.clientHeight + "px"; 
    feature.p.style.left = this.scaledWidth * feature.left - this.scaledDX + "px"; // calc the pixels to the right of the left edge of image - the amount left of the container 
} 

var features = [ 
    { 
     x: 375, 
     y: 190, 
     name: "right eye" 
    }, 
    { 
     x: 495, 
     y: 175, 
     name: "left eye" 
    }, 
    { 
     x: 445, 
     y: 255, 
     name: "nose" 
    }, 
    { 
     x: 260, 
     y: 45, 
     name: "right ear" 
    }, 
    { 
     x: 540, 
     y: 20, 
     name: "left ear" 
    } 
]; 

var x = new FeatureImage(document.getElementsByClassName("cat")[0], features, 800, 400); 
+0

감사합니다. 바이올린은 완벽하게 작동하며 내가 좋아하는 새로운 CSS 사양을 사용합니다. 그러나 나는 지금 옛 학교 방법으로 가야 할 것이다. – resting

+0

** 업데이트 ** 위치가 중앙에 가까워지지 않으면 다른 솔루션이 깨지게됩니다. – resting

+0

'vw''vh' 대안이 있습니까? 백그라운드 크기가 어떻게 조정되는지 알아낼 수 있다면 같은 알고리즘을 적용하면 오버레이를 배경 이미지와 적절하게 비율을 조정해야한다고 생각합니다. – resting

0

:

background-position:center center; 
background-size:cover; 

배경 이미지의 중심이 여전히 화면의 중앙에 있어야를 - 그, 그래서 그냥 시도, 상수로 편리 당신은 또한 화면의 중앙에 파인트 요소 센터 실제로 할 수있는 폭과 높이 속성을 추가 할 경우,

.place-on-eye { 
    ... 
    top: 50%; 
    left: 50%; 
} 

p.place-on-eye는 현재 단락의 왼쪽 상단 모서리가 화면의 중심에 당신과 함께 동일한 작업을 수행. 그래서 같은있다 :

.place-on-eye { 
    ... 
    width:50px; 
    height:50px; 
    text-align:center /* to make sure the text is center according to elements width */ 
    top: 50%; 
    left: 50%; 
    margin:-25px 0 0 -25px; 
} 

는 이제 p.place-on-eye의 중심은 배경 이미지의 중심처럼 화면의 정중앙에 있습니다. 고양이 눈 위로 가져 오려면 필요에 따라 왼쪽 및 위쪽 여백을 오프셋하면됩니다.

따라서 margin:-27px 0 0 -60px;과 같이해야합니다.

fiddle

0

. 줄의 끝에 검은 점이 겹쳐 져야합니다. 그러나이 솔루션은 실제 지점에서 약간의 비율로 약간 벗어납니다.

누군가 개선 할 수 있습니까?

JS :

$(function() { 
    function position_spot() { 
     w = $(window).width(); 
     h = $(window).height(); 
     wR = w/h; 

     // Point to place overlay based on 1397x1300 size 
     mT = 293; 
     mL = -195; 

     imgW = 1397; 
     imgH = 1300; 
     imgR = imgW/imgH; 

     tR = mT/imgH; // Top ratio 
     lR = mL/imgW; // Left ratio 

     wWr = w/imgW; // window width ratio to image 
     wHr = h/imgH; // window height ratio to image 

     if (wR > imgR) { 
      // backgroundimage size 
      h = imgH * wWr; 
      w = imgW * wWr; 
     } else { 
      h = imgH * wHr; 
      w = imgW * wHr; 
     } 
     $('.overlay-spot').css({ 
      'margin-top': h * tR, 
      'margin-left': w * lR 
     }); 
    } 
    $(window).resize(function() { 
     position_spot(); 
    }); 
    position_spot(); 

}); 
그것에게 그것의 위치
+0

나는 이것이 왜 잠시 동안 작동하지 않는지 알아 내려고했습니다. 모든 것이 올바르게 보였고 실제 이미지 너비가 1379px가 아니라 1397px라는 사실을 알게 된 것을 제외하고는 옳다고 생각합니다. 그걸 고쳐야 해! – peterjb

+0

네 말이 맞아. 1379px입니다. 꽤 좋아 보인다 :). 바이올린을 업데이트했습니다. – resting

관련 문제