Ken Ken - 5 months ago 9
jQuery Question

Text not centered on image

I am displaying a map for user's location and then showing a message on top of the map. I want to dynamically size the map (mapWidth & mapHeight) based on the user's device & window size and position the text in the center.

I'm using 50% top/left positioning, but often the text is not center positioned.



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>




Answer

The issue is because the containing div covers the entire width of the page. You should set it to display: inline-block instead. It would also be better to make the inner div cover the full width of its container and use text-align: center over left: 50%, otherwise you will have to calculate the width of the text manually and subtract half of that value to centralise the text. Try this:

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>

Comments