Home > Net >  Set CSS coordinates based on parent element
Set CSS coordinates based on parent element

Time:11-08

I have a game-level map image like this and I code by manual HTML - CSS - JS. I want to attach the level number based on the coordinates of the image but it moves to another position for another screen. I have used relative position for the parent element and absolute position for child elements. (I tried using px, em, rem, in, cm unit, but it hasn't worked well) enter image description here

I just want an idea for this problem. Thank you!

CodePudding user response:

I'm not sure if I get it right. You are trying to position the numbers relative to the whole background image? What are the other screen you refer? Can you show an actual screenshot of the issue?

I would do:

<div >
  <span id="span-1">1</span>
  <span id="span-2">2</span>
</div>

and then use PERCENTAGES to the determine the position of the numbers:

.image {
  position: relative;
  background: red;
  width: 100px;
  height: 100px;
}

span {
  position: absolute;
}

#span-1 {
  left: 55%;
}

#span-2{
  left: 20%;
  top: 75%;
}

Sandbox

CodePudding user response:

I think there are several ways to solve that problem. You mentioned like (I tried using px, em, rem, in, cm unit, but it hasn't worked well), it's true you failed because you tried with fixed amount.

In order to make sure the child image is fixed on the certain place of parent image, you should use dynamic amount like following alternative solutions.

  1. CSS

You can use percent in styling like.

position: absolute;
width: ###%;
height: ###%;
x: ###%;
y: ###%;
  1. You can use javascript.

When loads the initial screen, you can calculate the ratio of the parent width to screen's width. And you can apply it to the styling using CSS selector or ID.

  1. Update the design.

I think it's the proper and best solution. So you can update the design with map and markers together.

Hope it works for you!

  • Related