Home HTML position = center-10px
Reply: 3

HTML position = center-10px

Vítek Peterka
Vítek Peterka Published in 2017-12-07 21:50:13Z

I am making an HTML website. I have an map as an background picture and I need a button to be on the map. Like this:

But when I start scaling my site, this happens: I know what is the problem: the position of the pictures is center-X px and center-Y px, not margin: 40% 0px 0px 20%. But how to do that? position: absolute; left: 50%-30px; top: 50%-83px doesn´t work.

Chris Happy
Chris Happy Reply to 2017-12-07 22:03:55Z

You can use negative margins which has better support than calc().

position: absolute;
left: 50%;
top: 50%;
margin-top: -83px;
margin-left: -30px;

If you already have margins, you can just minus them from there. However, if they are defined as percentages or em's, then you're going to have to convert them accordingly.

Nerds of Technology
Nerds of Technology Reply to 2017-12-07 22:16:42Z

You will want the image to be relative to the background image (div container with the map as background image):

position: relative; left: 30px; top: 83px
Zze Reply to 2017-12-07 22:11:06Z

A bunch of people have mentioned using absolute margins (which would work), however there is another approach with the implementation of transform: translate.

In the example below, the inner img is always centered in its containing div which I believe would also meet your needs. I also added some random animation to the box so that you can see how effectively this positions itself.

setInterval(randomAnimation, 500);

function randomAnimation() {
  var random = Math.floor(Math.random() * (4 - 0));
  if (random == 0)
      top: "+=50"
  else if (random == 1)
      left: "+=50"
  else if (random == 2)
      top: "-=50"
      height: "+=50"
.box {
  position: relative;
  width: 150px;
  height: 100px;
  background-image: url(http://via.placeholder.com/150x100/ff0000/ffffff)

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box">
  <img src="http://via.placeholder.com/50x50" />

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.326362 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO