2016-06-15 10 views
1

私はユーザーの場所の地図を表示していて、地図の上にメッセージを表示しています。私は、ユーザーのデバイスの&ウィンドウサイズに基づいてマップ(mapWidth & mapHeight)のサイズを動的に変更し、テキストを中央に配置したいと考えています。テキストが画像の中央に配置されていません

私は50%の上/左の位置を使用していますが、テキストは中央に配置されていないことがよくあります。

var ip = '1.2.3.4'; 
 
var msg = 'Welcome User'; 
 

 
var mapUrl = 'https://maps.googleapis.com/maps/api/staticmap?center='; 
 
var mapWidth = 250; 
 
var mapHeight = 150; 
 
var mapParams = '&zoom=9&size='+mapWidth+'x'+mapHeight+'&scale=1'; 
 

 
var locationUrl = 'https://ipapi.co/'; 
 
var locationField = '/latlong/'; 
 

 
var updateMap = function(data){ 
 
    $('.map-img').attr('src', mapUrl + data + mapParams); 
 
    $('.ip').text(msg).fadeIn('slow'); 
 
}; 
 

 
$.get(locationUrl + ip + locationField, updateMap);
.ip { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div style="position:relative;"> 
 
    <img class="map-img" src=""> 
 
    <div class="ip"></div> 
 
</div>

答えて

1

含むdivは、ページの幅全体をカバーしているため問題があります。代わりにdisplay: inline-blockに設定する必要があります。また、を超えてleft: 50%を使用すると、テキストの幅を手動で計算し、その値の半分を引いてテキストを集中させる必要があります。これを試してみてください:

var ip = '1.2.3.4'; 
 
var msg = 'Welcome User'; 
 

 
var mapUrl = 'https://maps.googleapis.com/maps/api/staticmap?center='; 
 
var mapWidth = 250; 
 
var mapHeight = 150; 
 
var mapParams = '&zoom=9&size=' + mapWidth + 'x' + mapHeight + '&scale=1'; 
 

 
var locationUrl = 'https://ipapi.co/'; 
 
var locationField = '/latlong/'; 
 

 
var updateMap = function(data) { 
 
    $('.map-img').attr('src', mapUrl + data + mapParams); 
 
    $('.ip').text(msg).fadeIn('slow'); 
 
}; 
 

 
$.get(locationUrl + ip + locationField, updateMap);
.container { 
 
    display: inline-block; 
 
    position: relative; 
 
} 
 
.ip { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    text-align: center; 
 
    display: none; 
 
    margin-top: -0.5em; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="container"> 
 
    <img class="map-img" src=""> 
 
    <div class="ip"></div> 
 
</div>

+1

おかげで、私はそれを実現した後、コメントを削除しました。最初は左端が整列していた。 – Ken

0

使用を

.ip { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    display: none; 
 
    transform: translate(-50%, -50%); 
 
}

+0

これは垂直にセンタリングされていますが、水平ではありません。https://jsfiddle.net/07wfmf2e/を参照してください。 – Ken

関連する問題