Martin Adámek
Martin Adámek

Reputation: 18359

Scaling div to its parent while keeping absolute positions inside

I need to display an image (floor plan), place multiple icons (cameras) on top of it, and scale that image (its div container) to its parent.

If it would be just about the image, simple max-width: 100% works ok. But I need to maintain correct camera positions on top of it.

Following example shows my current status. Now I need to somehow scale the .container to fit the top level div (here I set 400px width, but in real life that will be dynamic/responsive), while keeping the camera icons on correct positions.

.container {
  position: relative;
}

.camera {
  position: absolute;
  display: flex;
  width: 30px;
  height: 30px;
  align-items: center;
  justify-content: center;
  transform: translate(-50%, -50%);
  background: darkred;
}
<div style="width: 400px">
  <div class="container">
    <img src="https://via.placeholder.com/600x400">
    <div class="camera" style="left: 50px; top: 50px"></div>
    <div class="camera" style="left: 300px; top: 50px"></div>
    <div class="camera" style="left: 550px; top: 350px"></div>
  </div>
</div>

Is this possible somehow via CSS? I know I could produce the floor plan with camera icons as SVG and scale just the image via max-width, but if possible, I would rather not construct the SVG.

Few notes:

I am looking for a CSS way, I know how to do this manually via JS, computing the scale factor manually and using transform: scale(...).

Upvotes: 2

Views: 1558

Answers (1)

Will Jenkins
Will Jenkins

Reputation: 9787

You could do it by positioning your cameras using %-ages rather than px (you could also make their sizes proportional too). Then you can change the size of the container and they'll stay positioned relative to it.

.container {
  position: relative;
}
#outer{
   border: 1px solid black;
}
.camera {
  position: absolute;
  width: 5%;
  height: 5%;
  align-items: center;
  justify-content: center;
  background: darkred;
}
img{
  width:100%;
}
<div style="width: 500px" id="outer">
  <div class="container">
    <img src="https://via.placeholder.com/600x400">
    <div class="camera" style="left: 5%; top: 5%"></div>
    <div class="camera" style="left: 30%; top: 20%"></div>
    <div class="camera" style="left: 50%; top: 50%"></div>
  </div>
</div>

 <div style="width: 200px" id="outer">
  <div class="container">
    <img src="https://via.placeholder.com/600x400">
    <div class="camera" style="left: 5%; top: 5%"></div>
    <div class="camera" style="left: 30%; top: 20%"></div>
    <div class="camera" style="left: 50%; top: 50%"></div>
  </div>
</div>

Upvotes: 4

Related Questions